Merge pull request #464 from samcharles93/feat/348-config-editing
Feat/348 config editing
This commit is contained in:
commit
5104c50953
39 files changed
+2689
-154
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
|
||||
)
|
||||
|
||||
// applyDottedOverlay decodes dotted-path updates into cfg. yaml cannot
|
||||
// decode dotted keys ("budgets.max_steps" is not a struct field), so
|
||||
// the updates are nested into a map first -- the same nesting the
|
||||
// overlay store's Snapshot performs -- then decoded with the same
|
||||
// field-level merge the file overlay uses. cfg must be a copy the
|
||||
// caller owns (a Clone of the published config); it is never decoded
|
||||
// into a published snapshot directly.
|
||||
func applyDottedOverlay(cfg *config.Config, updates map[string]any) error {
|
||||
nested := make(map[string]any)
|
||||
for key, value := range updates {
|
||||
if err := overlay.Nest(nested, key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return configuration.ApplyOverlayValues(cfg, nested)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// TestApplyDottedOverlayNestsBeforeDecode pins the PATCH-path fix: the
|
||||
// UI sends dotted keys ("budgets.max_steps") and yaml cannot decode a
|
||||
// dotted key as a struct field, so the updates must be nested first. A
|
||||
// regression here silently drops every dotted update while returning 200.
|
||||
func TestApplyDottedOverlayNestsBeforeDecode(t *testing.T) {
|
||||
cfg := config.Config{Budgets: config.Budgets{MaxSteps: 10}}
|
||||
if err := applyDottedOverlay(&cfg, map[string]any{"budgets.max_steps": 20}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Budgets.MaxSteps != 20 {
|
||||
t.Fatalf("MaxSteps = %d, want 20 (dotted key must be nested before decode)", cfg.Budgets.MaxSteps)
|
||||
}
|
||||
// A field the update does not name keeps its value.
|
||||
if cfg.Budgets.MaxTokens != 0 {
|
||||
t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyDottedOverlayRejectsEmptyKey pins that a malformed dotted key
|
||||
// fails instead of silently nesting under a synthetic root.
|
||||
func TestApplyDottedOverlayRejectsEmptyKey(t *testing.T) {
|
||||
cfg := config.Config{}
|
||||
if err := applyDottedOverlay(&cfg, map[string]any{"": 1}); err == nil {
|
||||
t.Fatal("empty dotted key accepted")
|
||||
}
|
||||
}
|
||||
+229
-6
@@ -16,8 +16,10 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
@@ -43,6 +45,7 @@ import (
|
||||
"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/configuration/overlay"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
@@ -293,6 +296,15 @@ func taskDBPath(configuredPath string) string {
|
||||
return configuredPath + "-tasks.sqlite"
|
||||
}
|
||||
|
||||
// configDBPath resolves the runtime config overlay file. It is a sibling
|
||||
// of the task and conversation stores (same configured path, own suffix)
|
||||
// so each file owns its user_version and its migrator with no
|
||||
// contention; recovery from a broken overlay is rm this file plus the
|
||||
// --no-config-overlay boot flag.
|
||||
func configDBPath(configuredPath string) string {
|
||||
return configuredPath + "-config.sqlite"
|
||||
}
|
||||
|
||||
func manualRequeueTask(ctx context.Context, st store.TaskStore, taskID int64) error {
|
||||
task, err := st.TaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
@@ -313,6 +325,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, "skip the runtime config overlay (recovery hatch for the DB overlay; the -config-overlay file overlay still applies)")
|
||||
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,12 +334,53 @@ func run() int {
|
||||
|
||||
log := slog.New(slog.NewJSONHandler(os.Stderr, nil))
|
||||
|
||||
doc, err := configuration.New(log).Resolve(*cfgPath, *overlayPath)
|
||||
loader := configuration.New(log)
|
||||
skipOverlay := *noConfigOverlay || configuration.SkipOverlay()
|
||||
if 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
|
||||
}
|
||||
// Runtime config overlay: dashboard-edited overrides layered over the
|
||||
// file config from their own SQLite file (own user_version and
|
||||
// migrator, no contention with the task store). Skipped under
|
||||
// --no-config-overlay / ARCHIE_SKIP_CONFIG_OVERLAY=1, or when the
|
||||
// store cannot be opened or its values fail validation -- a broken
|
||||
// overlay must not brick the daemon. bootOverlayErr carries the
|
||||
// degrade reason into /api/config's reload status so it is visible
|
||||
// where the operator is looking, not only in logs.
|
||||
var overlayStore *overlay.Store
|
||||
var bootOverlayErr atomic.Pointer[string]
|
||||
if !skipOverlay {
|
||||
overlayStore, err = overlay.Open(ctx, configDBPath(doc.Config.DBPath))
|
||||
if err != nil {
|
||||
reason := err.Error()
|
||||
bootOverlayErr.Store(&reason)
|
||||
log.Error("config overlay unavailable; booting on file config alone", "path", configDBPath(doc.Config.DBPath), "err", err)
|
||||
} else {
|
||||
defer overlayStore.Close()
|
||||
if overrides, err := overlayStore.Snapshot(ctx); err != nil {
|
||||
reason := err.Error()
|
||||
bootOverlayErr.Store(&reason)
|
||||
log.Error("config overlay unreadable; booting on file config alone", "err", err)
|
||||
} else if len(overrides) > 0 {
|
||||
applied, err := loader.ApplyOverlay(doc, overrides)
|
||||
if err != nil {
|
||||
reason := err.Error()
|
||||
bootOverlayErr.Store(&reason)
|
||||
log.Error("config overlay rejected by validation; booting on file config alone", "err", err)
|
||||
} else {
|
||||
doc = applied
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg := doc.Config
|
||||
var currentProvenance atomic.Pointer[configuration.Provenance]
|
||||
currentProvenance.Store(&doc.Provenance)
|
||||
|
||||
// Re-create the logger now the config is known. Everything above this
|
||||
// point logs to stderr only, which is unavoidable: the log destination is
|
||||
@@ -427,7 +481,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: &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")
|
||||
@@ -504,7 +559,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 +583,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 +608,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 +1005,8 @@ func run() int {
|
||||
// via Yaegi is deferred to the container/agent runtime.
|
||||
|
||||
d := &daemon.Daemon{
|
||||
Cfg: cfg,
|
||||
Cfg: config.NewHolder(cfg),
|
||||
ConnectedNATS: cfg.NATS,
|
||||
Store: st,
|
||||
Bus: bus,
|
||||
Forge: forgeClient,
|
||||
@@ -972,6 +1028,173 @@ func run() int {
|
||||
TaskLogs: taskLogs,
|
||||
}
|
||||
web.TaskStopper = d
|
||||
// web and the daemon must share ONE Holder: a reload swaps d.Cfg and
|
||||
// the dashboard reads the running config from the same snapshot. The
|
||||
// webui Holder seeded in the literal above is replaced here; after
|
||||
// this point /api/config and the daemon can never disagree about the
|
||||
// published config.
|
||||
web.Cfg = d.Cfg
|
||||
|
||||
// publishConfig publishes a config snapshot and its provenance to
|
||||
// both the daemon and the dashboard (they share one Holder). Reload
|
||||
// and the PATCH path both go through it, so the two can never
|
||||
// diverge. currentProvenance (an atomic) is the last published
|
||||
// provenance chain; the PATCH path appends the runtime-overlay
|
||||
// origin to it.
|
||||
publishConfig := func(cfg config.Config, provenance configuration.Provenance) {
|
||||
d.Cfg.Set(cfg)
|
||||
origins := make([]webui.ConfigOrigin, 0, len(provenance.Origins))
|
||||
for _, origin := range provenance.Origins {
|
||||
origins = append(origins, webui.ConfigOrigin{
|
||||
Path: origin.Path, Role: string(origin.Role), Layer: string(origin.Layer), Feature: string(origin.Feature),
|
||||
})
|
||||
}
|
||||
web.SetProvenance(origins)
|
||||
}
|
||||
|
||||
// SIGHUP re-loads the config from disk, layers the runtime overlay,
|
||||
// and republishes it. 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) {
|
||||
// Boot merges catalog-discovered providers into cfg before the
|
||||
// Holders are seeded; publishing the raw reloaded document would
|
||||
// drop them from the running config even though the file is
|
||||
// unchanged. Re-apply the same merge (idempotent: a catalog that
|
||||
// failed to load merges to identity).
|
||||
applyModelCatalog(&doc.Config, catalog)
|
||||
old := d.Cfg.Get()
|
||||
currentProvenance.Store(&doc.Provenance)
|
||||
publishConfig(doc.Config, doc.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())
|
||||
}
|
||||
})
|
||||
if overlayStore != nil {
|
||||
reloadController.WithOverlay(func() (map[string]any, error) { return overlayStore.Snapshot(ctx) })
|
||||
}
|
||||
// LastReload merges the reload controller's outcome with the boot-time
|
||||
// overlay degrade, so /api/config carries both the last reload result
|
||||
// and whether the runtime overlay is in effect at all.
|
||||
web.LastReload = func() config.ReloadStatus {
|
||||
st := reloadController.Status()
|
||||
if p := bootOverlayErr.Load(); p != nil {
|
||||
st.OverlayUnavailable = *p
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// PATCH /api/config goes through the same publish path as reload:
|
||||
// apply to a deep copy of the published config, validate the
|
||||
// materialised result, persist to the overlay, then publish. It must
|
||||
// never call Set directly from the handler -- web.Cfg is the daemon's
|
||||
// own Holder -- and it decodes into a Clone so a failed validation
|
||||
// cannot mutate the published snapshot's shared maps.
|
||||
web.UpdateConfig = func(ctx context.Context, updates map[string]any) error {
|
||||
if overlayStore == nil {
|
||||
return fmt.Errorf("%w: config overlay is disabled (--no-config-overlay or ARCHIE_SKIP_CONFIG_OVERLAY=1)", webui.ErrConfigUpdateUnavailable)
|
||||
}
|
||||
for key := range updates {
|
||||
if reason, denied := overlay.DeniedKeys[key]; denied {
|
||||
return fmt.Errorf("%w: config key %s is not runtime-tunable: %s", webui.ErrConfigUpdateInvalid, key, reason)
|
||||
}
|
||||
}
|
||||
next := d.Cfg.Get().Clone()
|
||||
if err := applyDottedOverlay(&next, updates); err != nil {
|
||||
return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
if err := configuration.Validate(&next); err != nil {
|
||||
return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
for key, value := range updates {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
if err := overlayStore.Set(ctx, key, string(data), "dashboard"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Provenance gets the runtime-overlay origin, replacing any prior
|
||||
// one so the chain does not grow unboundedly across edits.
|
||||
var kept []configuration.Origin
|
||||
for _, origin := range currentProvenance.Load().Origins {
|
||||
if origin.Path == "config_overlay (runtime)" {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, origin)
|
||||
}
|
||||
prov := configuration.Provenance{Origins: append(kept,
|
||||
configuration.Origin{Path: "config_overlay (runtime)", Role: configuration.RoleMain, Layer: configuration.LayerOverlay})}
|
||||
currentProvenance.Store(&prov)
|
||||
publishConfig(next, prov)
|
||||
bootOverlayErr.Store(nil) // a successful write proves the overlay works again
|
||||
log.Info("config updated from dashboard", "keys", len(updates))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ConfigOverrides lists the dotted keys currently overridden by the
|
||||
// runtime overlay, so the dashboard can mark those rows and offer a
|
||||
// reset. A disabled store reports no overrides.
|
||||
web.ConfigOverrides = func(ctx context.Context) ([]string, error) {
|
||||
if overlayStore == nil {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := overlayStore.Snapshot(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keys := make([]string, 0, len(rows))
|
||||
for k := range rows {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// ResetConfig deletes one overlay row and republishes file + remaining
|
||||
// overlay, so a dashboard-created override can be removed without
|
||||
// editing SQL -- and so an operator whose file edit is shadowed by an
|
||||
// override can recover it with one click. The file is resolved and
|
||||
// the target state validated BEFORE the row is deleted, so a broken
|
||||
// file cannot leave the store and the running config disagreeing.
|
||||
web.ResetConfig = func(ctx context.Context, key string) error {
|
||||
if overlayStore == nil {
|
||||
return fmt.Errorf("%w: config overlay is disabled", webui.ErrConfigUpdateUnavailable)
|
||||
}
|
||||
overrides, err := overlayStore.Snapshot(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
delete(overrides, key) // the target overlay state after the reset
|
||||
doc, err := loader.Resolve(*cfgPath, *overlayPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
if len(overrides) > 0 {
|
||||
if doc, err = loader.ApplyOverlay(doc, overrides); err != nil {
|
||||
return fmt.Errorf("%w: %w", webui.ErrConfigUpdateInvalid, err)
|
||||
}
|
||||
}
|
||||
if err := overlayStore.Delete(ctx, key); err != nil {
|
||||
return err
|
||||
}
|
||||
applyModelCatalog(&doc.Config, catalog)
|
||||
currentProvenance.Store(&doc.Provenance)
|
||||
publishConfig(doc.Config, doc.Provenance)
|
||||
bootOverlayErr.Store(nil)
|
||||
log.Info("config key reset to file value", "key", key)
|
||||
return nil
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
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). Must be
|
||||
// non-nil; newReloadController requires it.
|
||||
apply func(*configuration.Document)
|
||||
|
||||
// overlayValues, when non-nil, returns the runtime config overlay
|
||||
// (dotted keys -> typed values) to layer over the file config before
|
||||
// publishing. A failed overlay read or validation aborts the reload
|
||||
// exactly like a bad file.
|
||||
overlayValues func() (map[string]any, error)
|
||||
|
||||
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
|
||||
}
|
||||
if c.overlayValues != nil {
|
||||
values, err := c.overlayValues()
|
||||
if err != nil {
|
||||
c.status.Store(&config.ReloadStatus{
|
||||
LastError: err.Error(),
|
||||
LastErrorAt: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
return err
|
||||
}
|
||||
if len(values) > 0 {
|
||||
// ApplyOverlay never mutates its input: on failure the
|
||||
// resolved document (and the running config) is untouched.
|
||||
if doc, err = c.loader.ApplyOverlay(doc, values); 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
|
||||
}
|
||||
|
||||
// WithOverlay attaches the runtime config overlay source. Optional: a
|
||||
// controller without it publishes the file config alone.
|
||||
func (c *ReloadController) WithOverlay(fn func() (map[string]any, error)) *ReloadController {
|
||||
c.overlayValues = fn
|
||||
return c
|
||||
}
|
||||
|
||||
// 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 a reload takes effect on
|
||||
// without a restart. The criterion: a field is reloadable when EVERY
|
||||
// consumer re-reads it. That question read as "what does the daemon
|
||||
// re-read" while the daemon owned the only Holder; it stopped being
|
||||
// sufficient when webui began sharing that Holder, because webui
|
||||
// handlers re-read on every request. MaxRetries is the worked example:
|
||||
// its only consumer is api_tasks.go:380,383, reading per-request
|
||||
// s.Cfg.Get(), and nothing in the daemon reads it -- so it reloads.
|
||||
// Chat.Telegram.TokenEnv is the counter-example: webui reads it per
|
||||
// request AND a telegram bot built at startup consumes it, so it is
|
||||
// NOT reloadable, and treating "webui reads it" as sufficient would
|
||||
// display a new token while the bot uses the old one.
|
||||
//
|
||||
// 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: ForTask carries these into every dispatched
|
||||
// TaskContext (config.go ForTask), built fresh from d.Cfg.Get() at
|
||||
// dispatch. Pinned by TestReloadableFieldsCoverForTaskSnapshot so a
|
||||
// field added to ForTask cannot silently drift out of this list.
|
||||
"DiffCapLines": true,
|
||||
"Budgets": true,
|
||||
"Dispatch": true,
|
||||
"Models": true,
|
||||
"Notify": true,
|
||||
// Per-poll reads off the live config in pollIssuesWithConfig:
|
||||
// cfg.Label feeds IssuesWithLabel (daemon.go:359,390), cfg.BotUser
|
||||
// feeds AssignedIssues (:368,381). Not carried by ForTask, so
|
||||
// pinned by hand in TestReloadableFieldsCoverForTaskSnapshot.
|
||||
"Label": true,
|
||||
"BotUser": true,
|
||||
// Worked example of the every-consumer criterion above: the sole
|
||||
// consumer is the webui maxRetriesFor handler (api_tasks.go:380,383),
|
||||
// which re-reads per request; the daemon never reads MaxRetries. The
|
||||
// per-task half of this list is pinned mechanically; this webui-only
|
||||
// entry is pinned by TestChangedNonReloadableFields.
|
||||
"MaxRetries": true,
|
||||
}
|
||||
|
||||
// reloadableSubFields are sub-fields of structs that are otherwise
|
||||
// startup-built. VolumeTTL is re-read per cycle in cleanupExpiredStorage;
|
||||
// everything else in Containers (Image, Enabled, MaxConcurrency,
|
||||
// MaxUptime, PullPolicy, Network) is frozen in the startup-built
|
||||
// container pool -- the dispatchers re-read MaxConcurrency but the pool
|
||||
// captures it at construction (container/pool.go:94,163), so a change
|
||||
// only partially applies and must warn requires-restart. Forge.Host is
|
||||
// carried into TaskContext by ForTask (display/link building only); the
|
||||
// forge client itself is startup-built, so Type/Token/TokenEnv stay
|
||||
// requires-restart.
|
||||
var reloadableSubFields = map[string]map[string]bool{
|
||||
"Containers": {"VolumeTTL": true},
|
||||
"Forge": {"Host": 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, next config.Config) []string {
|
||||
var changed []string
|
||||
ov, nv := reflect.ValueOf(old), reflect.ValueOf(next)
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"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 TestReloadAppliesOverlayBeforePublish(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.toml")
|
||||
writeConfig(t, path, minimalConfigTOML("widget"))
|
||||
|
||||
loader := configuration.New(slog.New(slog.DiscardHandler))
|
||||
var published config.Config
|
||||
controller := newReloadController(loader, path, "", func(doc *configuration.Document) {
|
||||
published = doc.Config
|
||||
}).WithOverlay(func() (map[string]any, error) {
|
||||
return map[string]any{"poll_interval": "90s"}, nil
|
||||
})
|
||||
|
||||
if err := controller.Reload(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if published.PollInterval != config.Duration(90*time.Second) {
|
||||
t.Errorf("PollInterval = %v, want 90s (overlay applied before publish)", published.PollInterval)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadOverlayFailureAborts pins that a failed overlay read or
|
||||
// validation aborts the reload exactly like a bad file: apply is not
|
||||
// called and the error is recorded.
|
||||
func TestReloadOverlayFailureAborts(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++ }).
|
||||
WithOverlay(func() (map[string]any, error) {
|
||||
return nil, errors.New("overlay unreadable")
|
||||
})
|
||||
|
||||
if err := controller.Reload(); err == nil {
|
||||
t.Fatal("expected an error from the failed overlay")
|
||||
}
|
||||
if applied != 0 {
|
||||
t.Fatalf("apply called %d times after overlay failure, want 0", applied)
|
||||
}
|
||||
if st := controller.Status(); st.LastError == "" {
|
||||
t.Fatal("expected LastError recorded")
|
||||
}
|
||||
}
|
||||
|
||||
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 -> 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
|
||||
reloadableOnly.Models = map[string]string{"builder": "provider/model"}
|
||||
reloadableOnly.Notify = config.Notify{Webhook: "https://notify.example/hook"}
|
||||
reloadableOnly.Label = "archie"
|
||||
reloadableOnly.BotUser = "new-bot"
|
||||
reloadableOnly.Forge = config.Forge{Host: "https://new-forge.example"}
|
||||
reloadableOnly.MaxRetries = 5
|
||||
if got := changedNonReloadableFields(base, reloadableOnly); len(got) != 0 {
|
||||
t.Fatalf("reloadable-only: got %v, want []", got)
|
||||
}
|
||||
|
||||
// A non-reloadable change is named (Agent builds the startup runner).
|
||||
nonReloadable := base
|
||||
nonReloadable.Agent = config.Agent{Mode: "subprocess"}
|
||||
if got := changedNonReloadableFields(base, nonReloadable); len(got) != 1 || got[0] != "Agent" {
|
||||
t.Fatalf("Agent change: got %v, want [Agent]", 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
|
||||
// MaxConcurrency is NOT reloadable: the dispatchers re-read it but the
|
||||
// startup-built container pool captures it (container/pool.go:94), so
|
||||
// a change only partially applies and must warn requires-restart.
|
||||
if got := changedNonReloadableFields(c1, c3); len(got) != 1 || got[0] != "Containers.MaxConcurrency" {
|
||||
t.Fatalf("MaxConcurrency change: got %v, want [Containers.MaxConcurrency]", 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)
|
||||
}
|
||||
|
||||
// Forge.Host is reloadable but Forge.Type is not: only the host is
|
||||
// carried into TaskContext by ForTask.
|
||||
forgeTypeChanged := base
|
||||
forgeTypeChanged.Forge = config.Forge{Type: "gitea"}
|
||||
if got := changedNonReloadableFields(base, forgeTypeChanged); len(got) != 1 || got[0] != "Forge.Type" {
|
||||
t.Fatalf("Forge.Type change: got %v, want [Forge.Type]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReloadableFieldsCoverForTaskSnapshot pins the allowlist against
|
||||
// the per-dispatch snapshot: every field ForTask carries into a
|
||||
// TaskContext is re-read at dispatch, so a reload applies to new tasks.
|
||||
// If a field is added to ForTask later, this test fails until the
|
||||
// allowlist is updated -- a hand-maintained list that mirrors ForTask
|
||||
// otherwise drifts silently into a wrong 'requires a restart' warning.
|
||||
func TestReloadableFieldsCoverForTaskSnapshot(t *testing.T) {
|
||||
tt := reflect.TypeFor[config.TaskConfig]()
|
||||
for field := range tt.Fields() {
|
||||
name := field.Name
|
||||
if name == "Forge" {
|
||||
// TaskConfig.Forge is TaskForge{Host}; it maps to the
|
||||
// Config.Forge.Host sub-field allowlist entry.
|
||||
if !reloadableSubFields["Forge"]["Host"] {
|
||||
t.Errorf("ForTask field Forge (Host) is not allowlisted as reloadable")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !reloadableFields[name] {
|
||||
t.Errorf("ForTask field %s is not allowlisted as reloadable", name)
|
||||
}
|
||||
}
|
||||
// The poll-path fields (Label, BotUser) are not carried by ForTask;
|
||||
// pin them explicitly so a refactor that moves their read site does
|
||||
// not silently drop the allowlist entry.
|
||||
for _, name := range []string{"Label", "BotUser"} {
|
||||
if !reloadableFields[name] {
|
||||
t.Errorf("poll-path field %s is not allowlisted as reloadable", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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+`"}`))
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -244,6 +244,10 @@ The application currently changes behavioural values through unrelated paths:
|
||||
| Persona selection | `PersonaRegistry.SetActive` mutates an in-memory per-session choice. | Agent-system session state. Persistence and audit requirements are owned by that domain, not the configuration loader. |
|
||||
| Memory provider `SaveConfig` | Accepts an untyped map, delegates validation/persistence to an optional provider interface, then providers reload backing files. | A typed provider-owned configuration command using candidate validation, versioning, atomic promotion, health observation, audit, and rollback. |
|
||||
| File and environment overlays | Applied while loading `internal/config`; defaults are filled by mutation in `finalize`. | Configuration-infrastructure input processing that produces separately typed candidates. Defaults and derivations remain visible in provenance. |
|
||||
| SIGHUP config reload (2026-08) | Re-resolves the file config (+ the runtime overlay), validates, then atomically republishes through `config.Holder`. A failed reload keeps the running config and records `last_error`/`last_error_at` in `/api/config`. | Candidate promotion with last-known-good retention: the running snapshot is untouched on failure. A bounded observation period and actor audit are not yet implemented. |
|
||||
| Dashboard PATCH `/api/config` (2026-08) | Applies dotted-key updates to a deep copy of the published config, validates the materialised result, persists to the runtime overlay, then republishes. Denylisted keys (`db_path`, `work_dir`) return 400; a rejected candidate never reaches `Set`. | The universal change protocol's validate-stage-promote path with the overlay store as persistence. Actor is recorded as `dashboard`; no per-field health observation or versioned audit trail yet. |
|
||||
| Dashboard reset `POST /api/config/reset` (2026-08) | Deletes one overlay row after resolving and validating the target state, then republishes file + remaining overlay, so a dashboard-created override can be removed without editing SQL. | Remediation/rollback: the last-known-good (file) value is restored for that key. |
|
||||
| Runtime config overlay store (2026-08) | Dashboard-edited overrides in `cfg.DBPath + "-config.sqlite"` (own `user_version`, own migrator), layered over the file config at boot and on every reload. A broken overlay degrades to file config alone, surfaced via `ReloadStatus.OverlayUnavailable`. | External configuration storage for runtime-tunable values, separate from the task/conversation stores so each file owns its migration. The `--no-config-overlay` / `ARCHIE_SKIP_CONFIG_OVERLAY=1` recovery hatch skips it entirely. |
|
||||
|
||||
Any further mutation seam discovered during migration MUST be added here before
|
||||
it is changed. Direct field assignment on a live settings object is prohibited.
|
||||
@@ -274,6 +278,81 @@ Settings that cannot safely reload in-process are marked restart-required. The
|
||||
change may still be validated and versioned immediately, but promotion occurs
|
||||
through a controlled restart with the same health and rollback semantics.
|
||||
|
||||
## Implemented runtime reload and config overlay (2026-08)
|
||||
|
||||
A first implementation of the universal change protocol now exists for the
|
||||
runtime-tunable surface: SIGHUP reload, the dashboard PATCH, and the runtime
|
||||
config overlay. The mechanics below are the current implementation; the
|
||||
aspirational protocol (bounded observation, versioned audit trail, per-actor
|
||||
audit) remains future work.
|
||||
|
||||
### Published snapshot: `config.Holder`
|
||||
|
||||
The running configuration is a published snapshot held in `config.Holder`
|
||||
(`internal/config/holder.go`). Get returns a value under RLock; Set replaces the
|
||||
whole snapshot. A published Config is immutable: reload constructs a fresh one
|
||||
and calls Set. `config.Clone` deep-copies every reference-type field so a failed
|
||||
decode cannot mutate the published snapshot's shared maps. `Holder.Get` panics
|
||||
on a nil receiver — a forgotten `NewHolder` must fail loudly, not boot a daemon
|
||||
that silently runs on an empty config.
|
||||
|
||||
### The reloadable-field criterion
|
||||
|
||||
The diff-and-warn on reload asks whether a changed field takes effect without a
|
||||
restart. The criterion is: **a field is reloadable when every consumer re-reads
|
||||
it.** That question read as "what does the daemon re-read" while the daemon owned
|
||||
the only Holder; it stopped being sufficient when webui began sharing that
|
||||
Holder, because webui handlers re-read on every request. The allowlist lives in
|
||||
`cmd/archied/reload.go` and is deliberately a deny-by-default list: a field added
|
||||
to Config later defaults to requires-restart, forcing whoever adds it to decide
|
||||
deliberately. A reload that changes any non-allowlisted field logs
|
||||
"requires a restart" with the field names; a fully-applied reload logs Info.
|
||||
|
||||
### SIGHUP reload
|
||||
|
||||
SIGHUP re-resolves the file config (plus the runtime overlay), validates, and
|
||||
atomically republishes through the shared Holder. A failed reload — bad file,
|
||||
bad overlay — keeps the running config and records `last_error`/`last_error_at`
|
||||
in `/api/config` so the stale state is visible where the operator is looking.
|
||||
The three poll tickers re-read `PollInterval` per iteration and reset on change,
|
||||
so a reloaded interval genuinely takes effect.
|
||||
|
||||
### The runtime config overlay
|
||||
|
||||
The dashboard's edits persist to a dedicated SQLite file
|
||||
(`cfg.DBPath + "-config.sqlite"`, its own `user_version` and migrator — no
|
||||
contention with the task or conversation stores). The `config_overlay` table
|
||||
stores dotted-path keys with JSON-encoded values; the daemon layers them over
|
||||
the file config at boot and on every reload, with the same field-level
|
||||
precedence as a file overlay.
|
||||
|
||||
- **Denylist:** `db_path` and `work_dir` cannot be set (the daemon must read them
|
||||
before it can open the overlay store; changing them could break the next
|
||||
boot). Enforced at write time with a 400 and in the store.
|
||||
- **Bootstrap degrade:** a broken overlay (unopenable store, unreadable value,
|
||||
values failing validation) degrades to file config alone — it must not brick
|
||||
the daemon. The reason is surfaced via `ReloadStatus.OverlayUnavailable` in
|
||||
`/api/config` and rendered as a banner by the dashboard.
|
||||
- **Recovery hatch:** `--no-config-overlay` / `ARCHIE_SKIP_CONFIG_OVERLAY=1`
|
||||
skips the overlay entirely; removing the `-config.sqlite` file is the
|
||||
documented manual recovery. See safe-change-and-recovery.md.
|
||||
- **Shadowed file edits are visible:** `/api/config` reports which dotted keys
|
||||
the overlay currently sets (`overridden`), so the dashboard marks those rows and
|
||||
offers a per-row reset.
|
||||
|
||||
### Dashboard PATCH and reset
|
||||
|
||||
`PATCH /api/config` receives `{"updates": {"dotted.key": value}}`. It applies the
|
||||
updates to a deep copy of the published config, validates the materialised
|
||||
result, persists to the overlay, then republishes — it never calls Set directly
|
||||
from the handler, since the dashboard shares the daemon's Holder. Dotted keys
|
||||
are nested before decode (yaml cannot decode a dotted key as a struct field).
|
||||
Error classification: 400 for a denylisted key or failed validation, 503 when
|
||||
the overlay is disabled, 500 for a persistence failure. `POST /api/config/reset`
|
||||
deletes one overlay row after resolving and validating the target state,
|
||||
restoring the file value — the answer to "my file edit isn't taking effect
|
||||
because an override shadows it".
|
||||
|
||||
## Completion criteria
|
||||
|
||||
The configuration rearchitecture is complete only when:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Safe Change and Recovery
|
||||
|
||||
**Status:** Requirements approved; mechanics are under design
|
||||
**Status:** Requirements approved; mechanics are under design. The runtime config overlay subset is implemented (2026-08): see the degrade/recovery section below. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.
|
||||
**Date:** 2026-07-28
|
||||
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
|
||||
|
||||
@@ -100,6 +100,41 @@ capabilities continue operating.
|
||||
Remediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT
|
||||
silently oscillate between versions or retry forever.
|
||||
|
||||
## Runtime config overlay: degrade paths and recovery (2026-08)
|
||||
|
||||
The dashboard edits runtime-tunable settings into a dedicated overlay store
|
||||
(`cfg.DBPath + "-config.sqlite"`), layered over the file config at boot and on
|
||||
reload. The file remains the authoritative, editor-reachable source; the overlay
|
||||
is a runtime-tunable overlay on top of it. A broken overlay must never brick
|
||||
the daemon, for the same reason a bad file edit must not: the operator needs a
|
||||
path back that does not depend on the daemon's health.
|
||||
|
||||
### Degrade paths (all verified by the reload design)
|
||||
|
||||
| Failure | Boot behaviour | Where the operator sees it |
|
||||
| --- | --- | --- |
|
||||
| Overlay store cannot be opened (permissions, corrupt file) | Boots on file config alone; logs at error level | `/api/config` → `reload.overlay_unavailable` → dashboard banner |
|
||||
| Overlay snapshot unreadable (a row holds invalid JSON) | Boots on file config alone | Same |
|
||||
| Overlay values fail validation | Boots on file config alone; the overlay is rejected wholesale, never partially applied | Same |
|
||||
| SIGHUP reload with a bad file or bad overlay | Running config is kept; the reload records `last_error` / `last_error_at` | `/api/config` → `reload.last_error` → dashboard banner |
|
||||
|
||||
The overlay degrade paths never partially apply: `Loader.ApplyOverlay` decodes
|
||||
into a deep copy (`config.Clone`) and validates before anything is published,
|
||||
so a rejected overlay leaves the boot config exactly as the file produced it.
|
||||
|
||||
### Recovery
|
||||
|
||||
1. **`--no-config-overlay`** (or `ARCHIE_SKIP_CONFIG_OVERLAY=1`) boots the
|
||||
daemon on file config alone, ignoring the overlay entirely. This is the escape
|
||||
hatch that works when the daemon will not start.
|
||||
2. **Remove the overlay file** (`rm <dbpath>-config.sqlite`) — the overlay is
|
||||
recreated empty on next boot, so the daemon returns to pure file config.
|
||||
3. **Dashboard reset** (`POST /api/config/reset`) removes a single override
|
||||
whose file edit is shadowed, without stopping the daemon.
|
||||
|
||||
These are the documented recovery paths; they are deliberate, bounded, and do
|
||||
not require hand-editing SQL in a shared database.
|
||||
|
||||
## Gateway restart: two constraints learned the hard way
|
||||
|
||||
Telegram `/restart` (`internal/channels/telegram/restart.go` plus the `Start`
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestConfigCloneDeepCopiesReferenceFields pins that Clone returns a
|
||||
// value sharing no memory with the original: mutating the clone's maps
|
||||
// and slices must not touch the original. A shallow copy here would
|
||||
// silently let a failed overlay decode mutate the published snapshot.
|
||||
func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) {
|
||||
enabled := true
|
||||
orig := Config{
|
||||
Models: map[string]string{"builder": "m"},
|
||||
Repos: []Repo{{Gate: [][]string{{"task", "check"}}, Protect: []string{"p"}}},
|
||||
Identities: []IdentityConfig{{
|
||||
Models: map[string]string{"planner": "m2"},
|
||||
Repos: []Repo{{Gate: [][]string{{"go", "vet"}}}},
|
||||
}},
|
||||
Dispatch: Dispatch{Labels: map[string]string{"q": "archie:q"}},
|
||||
Tools: ToolsConfig{
|
||||
MCPServers: []MCPServer{{Headers: map[string]string{"A": "b"}, Args: []string{"x"}}},
|
||||
WebFetch: WebFetchConfig{Enabled: &enabled},
|
||||
},
|
||||
Memory: MemoryConfig{ProviderConfig: map[string]string{"k": "v"}},
|
||||
Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}},
|
||||
Agent: Agent{Env: []string{"HOME"}},
|
||||
Extra: map[string]any{"custom": 1},
|
||||
}
|
||||
|
||||
got := orig.Clone()
|
||||
got.Models["builder"] = "changed"
|
||||
got.Repos[0].Gate[0][0] = "changed"
|
||||
got.Repos[0].Protect[0] = "changed"
|
||||
got.Identities[0].Models["planner"] = "changed"
|
||||
got.Identities[0].Repos[0].Gate[0][0] = "changed"
|
||||
got.Dispatch.Labels["q"] = "changed"
|
||||
got.Tools.MCPServers[0].Headers["A"] = "changed"
|
||||
got.Tools.MCPServers[0].Args[0] = "changed"
|
||||
got.Memory.ProviderConfig["k"] = "changed"
|
||||
got.Chat.Telegram.AllowedUserIDs[0] = 99
|
||||
got.Agent.Env[0] = "changed"
|
||||
got.Extra["custom"] = 2
|
||||
*got.Tools.WebFetch.Enabled = false
|
||||
|
||||
if orig.Models["builder"] != "m" {
|
||||
t.Error("Models map is shared")
|
||||
}
|
||||
if orig.Repos[0].Gate[0][0] != "task" || orig.Repos[0].Protect[0] != "p" {
|
||||
t.Error("Repo nested slices are shared")
|
||||
}
|
||||
if orig.Identities[0].Models["planner"] != "m2" || orig.Identities[0].Repos[0].Gate[0][0] != "go" {
|
||||
t.Error("Identity nested fields are shared")
|
||||
}
|
||||
if orig.Dispatch.Labels["q"] != "archie:q" {
|
||||
t.Error("Dispatch.Labels map is shared")
|
||||
}
|
||||
if orig.Tools.MCPServers[0].Headers["A"] != "b" || orig.Tools.MCPServers[0].Args[0] != "x" {
|
||||
t.Error("MCP server fields are shared")
|
||||
}
|
||||
if orig.Memory.ProviderConfig["k"] != "v" {
|
||||
t.Error("Memory.ProviderConfig is shared")
|
||||
}
|
||||
if orig.Chat.Telegram.AllowedUserIDs[0] != 1 {
|
||||
t.Error("Telegram.AllowedUserIDs is shared")
|
||||
}
|
||||
if orig.Agent.Env[0] != "HOME" {
|
||||
t.Error("Agent.Env is shared")
|
||||
}
|
||||
if orig.Extra["custom"] != 1 {
|
||||
t.Error("Extra map is shared")
|
||||
}
|
||||
if !*orig.Tools.WebFetch.Enabled {
|
||||
t.Error("WebFetch.Enabled pointer is shared")
|
||||
}
|
||||
}
|
||||
@@ -489,6 +489,87 @@ func cloneStringMap(src map[string]string) map[string]string {
|
||||
return dst
|
||||
}
|
||||
|
||||
// Clone returns a deep copy of c: every reference-type field (maps,
|
||||
// slices, and the reference fields nested inside them) is copied, so
|
||||
// mutating the returned value cannot touch c or anything sharing memory
|
||||
// with it. It is used before the runtime overlay (or a dashboard PATCH)
|
||||
// decodes into a snapshot, so a failed or partial decode cannot mutate
|
||||
// the published config -- Holder.Get returns a shallow copy whose maps
|
||||
// are shared with the published snapshot.
|
||||
func (c Config) Clone() Config {
|
||||
c.Models = cloneStringMap(c.Models)
|
||||
c.Providers = maps.Clone(c.Providers)
|
||||
c.Dispatch.Labels = cloneStringMap(c.Dispatch.Labels)
|
||||
c.Agent.Env = append([]string(nil), c.Agent.Env...)
|
||||
c.Repos = cloneRepos(c.Repos)
|
||||
c.Identities = cloneIdentities(c.Identities)
|
||||
c.Chat.Models = append([]string(nil), c.Chat.Models...)
|
||||
c.Chat.Telegram.AllowedUserIDs = append([]int64(nil), c.Chat.Telegram.AllowedUserIDs...)
|
||||
c.Chat.Telegram.UpdateCheckCommand = append([]string(nil), c.Chat.Telegram.UpdateCheckCommand...)
|
||||
c.Chat.Telegram.UpdateInstallCommand = append([]string(nil), c.Chat.Telegram.UpdateInstallCommand...)
|
||||
c.Tools.MCPServers = cloneMCPServers(c.Tools.MCPServers)
|
||||
c.Memory.ProviderConfig = maps.Clone(c.Memory.ProviderConfig)
|
||||
if c.Tools.WebFetch.Enabled != nil {
|
||||
v := *c.Tools.WebFetch.Enabled
|
||||
c.Tools.WebFetch.Enabled = &v
|
||||
}
|
||||
c.Extra = maps.Clone(c.Extra)
|
||||
return c
|
||||
}
|
||||
|
||||
func cloneRepos(repos []Repo) []Repo {
|
||||
if repos == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]Repo, len(repos))
|
||||
for i, r := range repos {
|
||||
r.Gate = cloneStringSlices(r.Gate)
|
||||
r.Protect = append([]string(nil), r.Protect...)
|
||||
r.Preflight = cloneStringSlices(r.Preflight)
|
||||
out[i] = r
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneIdentities(ids []IdentityConfig) []IdentityConfig {
|
||||
if ids == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]IdentityConfig, len(ids))
|
||||
for i, id := range ids {
|
||||
id.Models = cloneStringMap(id.Models)
|
||||
id.Providers = maps.Clone(id.Providers)
|
||||
id.Dispatch.Labels = cloneStringMap(id.Dispatch.Labels)
|
||||
id.Repos = cloneRepos(id.Repos)
|
||||
out[i] = id
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneMCPServers(servers []MCPServer) []MCPServer {
|
||||
if servers == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]MCPServer, len(servers))
|
||||
for i, s := range servers {
|
||||
s.Args = append([]string(nil), s.Args...)
|
||||
s.Headers = maps.Clone(s.Headers)
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneStringSlices(ss [][]string) [][]string {
|
||||
if ss == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([][]string, len(ss))
|
||||
for i, s := range ss {
|
||||
out[i] = append([]string(nil), s...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// NATSConfig configures NATS JetStream for task distribution. When URL is
|
||||
// empty the existing SQLite ClaimNext flow is used unchanged.
|
||||
type NATSConfig struct {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
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 (a SIGHUP reload re-calling Loader.Resolve, 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.
|
||||
//
|
||||
// # Torn reads across a field group
|
||||
//
|
||||
// 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()
|
||||
// if cfg.PollInterval > 0 { ... }
|
||||
// for _, r := range cfg.Repos { ... }
|
||||
//
|
||||
// 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
|
||||
//
|
||||
// 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. Get panics on a nil
|
||||
// receiver; a forgotten NewHolder is a programming error. See the type
|
||||
// doc comment.
|
||||
func (h *Holder) Get() 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. Set panics on
|
||||
// a nil receiver.
|
||||
func (h *Holder) Set(c Config) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.cfg = c
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
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 range writers {
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range iters {
|
||||
h.Set(Config{BotUser: "w"})
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range iters {
|
||||
_ = h.Get()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestHolderGetPanicsOnNil(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("Get on nil Holder did not panic")
|
||||
}
|
||||
}()
|
||||
var h *Holder
|
||||
_ = h.Get()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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"`
|
||||
// OverlayUnavailable is the reason the runtime config overlay is not
|
||||
// in effect, so the running config is file-only. Set at boot when
|
||||
// the overlay store cannot be opened or its values fail validation,
|
||||
// and cleared by a successful dashboard write or reset. The
|
||||
// dashboard shows it so a boot-time degrade is visible where the
|
||||
// operator is looking, not only in logs.
|
||||
OverlayUnavailable string `json:"overlay_unavailable,omitempty"`
|
||||
}
|
||||
+61
-25
@@ -47,14 +47,23 @@ type TaskBus interface {
|
||||
}
|
||||
|
||||
type Daemon struct {
|
||||
Cfg config.Config
|
||||
Store store.TaskStore
|
||||
Forge forge.Forge
|
||||
Trees *worktree.Manager
|
||||
Agent agentexec.Runner
|
||||
Bus *events.Bus
|
||||
Workflows workflow.Registry
|
||||
Log *slog.Logger
|
||||
// Cfg publishes the running configuration. Read through Cfg() so a
|
||||
// reload swaps the published snapshot atomically. See config.Holder.
|
||||
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
|
||||
@@ -197,7 +206,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 +222,8 @@ func (d *Daemon) Run(ctx context.Context) error {
|
||||
if len(d.Identities) > 0 {
|
||||
return d.runIdentities(ctx)
|
||||
}
|
||||
ticker := time.NewTicker(d.Cfg.PollInterval.Std())
|
||||
interval := d.Cfg.Get().PollInterval.Std()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
d.Cycle(ctx)
|
||||
@@ -221,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,7 +264,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()
|
||||
}
|
||||
@@ -260,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)
|
||||
@@ -267,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.PollInterval.Std())
|
||||
interval := d.Cfg.Get().PollInterval.Std()
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
d.maintainAndDrain(ctx)
|
||||
@@ -275,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -288,7 +321,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 +415,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 +432,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 +451,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 +568,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 +719,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.
|
||||
@@ -1072,8 +1105,11 @@ func (d *Daemon) requestTaskRun(ctx context.Context, taskID int64, data []byte)
|
||||
|
||||
func (d *Daemon) containerEnv(task *store.Task) []string {
|
||||
var env []string
|
||||
env = append(env, "NATS_URL="+d.Cfg.NATS.URL)
|
||||
if tokenEnv := d.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)
|
||||
}
|
||||
@@ -1090,9 +1126,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 +1188,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
|
||||
}
|
||||
|
||||
@@ -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,18 @@ func TestAllowConcurrentForTaskPrefersOwningIdentityRepo(t *testing.T) {
|
||||
func TestContainerEnvIncludesConfiguredNATSCredentials(t *testing.T) {
|
||||
t.Setenv("ARCHIE_NATS_SECRET", "test-nats-token")
|
||||
|
||||
d := &Daemon{Cfg: 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{
|
||||
@@ -327,9 +333,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 +377,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 +538,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 {
|
||||
@@ -593,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
|
||||
@@ -677,7 +733,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 +807,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 +870,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 +878,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 +914,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 +1001,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.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
// ApplyOverlayValues decodes overrides (a nested map of dotted-path
|
||||
// values, as produced by the overlay store) into cfg using the same
|
||||
// field-level precedence as a file overlay: only the keys present are
|
||||
// replaced, every field the overlay omits keeps its existing value.
|
||||
//
|
||||
// This is the decode half of the runtime config overlay. The loader's
|
||||
// ApplyOverlay wraps it with defaulting, validation and provenance; the
|
||||
// dashboard PATCH path calls it on a copy of the published config and
|
||||
// validates the materialised result before persisting. Either way the
|
||||
// caller owns the cfg value -- pass a copy when the base must survive.
|
||||
func ApplyOverlayValues(cfg *config.Config, overrides map[string]any) error {
|
||||
if len(overrides) == 0 {
|
||||
return nil
|
||||
}
|
||||
data, err := yaml.Marshal(overrides)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: encoding config overlay: %v", ErrUnreadable, err)
|
||||
}
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
return fmt.Errorf("%w: parsing config overlay: %v", ErrUnreadable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package configuration
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
)
|
||||
|
||||
func TestApplyOverlayValuesFieldLevelMerge(t *testing.T) {
|
||||
cfg := config.Config{
|
||||
BotUser: "a",
|
||||
Budgets: config.Budgets{MaxSteps: 10},
|
||||
}
|
||||
overrides := map[string]any{
|
||||
"budgets": map[string]any{"max_steps": float64(20)},
|
||||
}
|
||||
if err := ApplyOverlayValues(&cfg, overrides); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Budgets.MaxSteps != 20 {
|
||||
t.Errorf("MaxSteps = %d, want 20", cfg.Budgets.MaxSteps)
|
||||
}
|
||||
// Fields the overlay omits keep their value.
|
||||
if cfg.BotUser != "a" {
|
||||
t.Errorf("BotUser = %q, want a (unchanged)", cfg.BotUser)
|
||||
}
|
||||
// Unrelated nested fields keep their value too.
|
||||
if cfg.Budgets.MaxTokens != 0 {
|
||||
t.Errorf("MaxTokens = %d, want 0 (untouched)", cfg.Budgets.MaxTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
l := New(slog.New(slog.DiscardHandler))
|
||||
doc, err := l.Resolve(path, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
applied, err := l.ApplyOverlay(doc, map[string]any{"poll_interval": "90s"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if applied.Config.PollInterval != config.Duration(90*time.Second) {
|
||||
t.Errorf("PollInterval = %v, want 90s", applied.Config.PollInterval)
|
||||
}
|
||||
if len(applied.Provenance.Origins) != 2 {
|
||||
t.Errorf("Origins = %+v, want 2 (file + runtime overlay)", applied.Provenance.Origins)
|
||||
}
|
||||
|
||||
// An overlay that fails validation aborts; ApplyOverlay never mutates
|
||||
// its input, so the base document is untouched even without a copy.
|
||||
if _, err := l.ApplyOverlay(doc, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil {
|
||||
t.Fatal("invalid overlay accepted")
|
||||
}
|
||||
if doc.Config.Agent.Mode != "inprocess" {
|
||||
t.Errorf("base Agent.Mode = %q, want inprocess (defaulted, untouched)", doc.Config.Agent.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoaderApplyOverlayEmptyIsNoOp(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.toml")
|
||||
if err := os.WriteFile(path, []byte("bot_user = \"widget\"\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := New(slog.New(slog.DiscardHandler))
|
||||
doc, err := l.Resolve(path, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
applied, err := l.ApplyOverlay(doc, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(applied.Provenance.Origins) != 1 {
|
||||
t.Errorf("Origins = %+v, want 1 (no overlay origin for an empty overlay)", applied.Provenance.Origins)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -113,6 +113,30 @@ func (l *Loader) Overlay(basePath, overlayPath string) (*Document, error) {
|
||||
return l.overlayFile(basePath, overlayPath)
|
||||
}
|
||||
|
||||
// ApplyOverlay decodes the runtime config overlay (a nested map of
|
||||
// dotted-path values from the overlay store) into a copy of doc with the
|
||||
// same field-level precedence as a file overlay, records the overlay
|
||||
// origin, then applies defaults and validates. It is used at boot and on
|
||||
// reload to layer dashboard-edited overrides over the file config.
|
||||
//
|
||||
// ApplyOverlay never mutates its input: the returned Document owns fresh
|
||||
// copies of the Config and the provenance chain, so a decode or
|
||||
// validation failure leaves the caller's document (and whatever it was
|
||||
// published from) exactly as it was.
|
||||
func (l *Loader) ApplyOverlay(doc *Document, overrides map[string]any) (*Document, error) {
|
||||
next := *doc
|
||||
next.Config = doc.Config.Clone()
|
||||
next.Provenance.Origins = append([]Origin(nil), doc.Provenance.Origins...)
|
||||
if len(overrides) == 0 {
|
||||
return l.finalize(&next)
|
||||
}
|
||||
if err := ApplyOverlayValues(&next.Config, overrides); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
next.Provenance.record(Origin{Path: "config_overlay (runtime)", Role: RoleMain, Layer: LayerOverlay})
|
||||
return l.finalize(&next)
|
||||
}
|
||||
|
||||
func (l *Loader) overlayFile(basePath, overlayPath string) (*Document, error) {
|
||||
doc := &Document{}
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
// Package overlay persists runtime-tunable configuration overrides in
|
||||
// their own SQLite file (cfg.DBPath + "-config.sqlite"), separate from
|
||||
// the task, conversation and search stores so each file owns its
|
||||
// user_version and its migrator with no contention.
|
||||
//
|
||||
// It backs the dashboard's config editing: a PATCH writes here, the
|
||||
// daemon layers these values over the file config at boot and on every
|
||||
// reload, and removing the file (or passing --no-config-overlay /
|
||||
// ARCHIE_SKIP_CONFIG_OVERLAY=1) is the documented recovery from a write
|
||||
// that would otherwise break boot.
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// DeniedKeys are the config keys the overlay may never set, mapped to
|
||||
// the reason shown to the operator. db_path is the daemon's own
|
||||
// bootstrap path -- the daemon must read it before it can open this
|
||||
// store -- and work_dir pins the whole working layout. Enforced at
|
||||
// write time (the API returns 4xx) and again in Set, not silently
|
||||
// dropped at read time.
|
||||
var DeniedKeys = map[string]string{
|
||||
"db_path": "required for bootstrap; cannot be changed at runtime",
|
||||
"work_dir": "pins the daemon's working layout; cannot be changed at runtime",
|
||||
}
|
||||
|
||||
// Store is the config overlay database.
|
||||
type Store struct{ db *sql.DB }
|
||||
|
||||
const schemaVersion = 1
|
||||
|
||||
const schema = `
|
||||
CREATE TABLE IF NOT EXISTS config_overlay (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
updated_by TEXT NOT NULL
|
||||
);
|
||||
`
|
||||
|
||||
// Open opens (creating if needed) the overlay database and migrates it.
|
||||
func Open(ctx context.Context, path string) (*Store, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db, err := sql.Open("sqlite", sqliteDSN(path))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err := db.ExecContext(ctx, schema); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("overlay: init schema: %w", err), db.Close())
|
||||
}
|
||||
if err := migrate(ctx, db); err != nil {
|
||||
return nil, errors.Join(fmt.Errorf("overlay: migrate: %w", err), db.Close())
|
||||
}
|
||||
return &Store{db: db}, nil
|
||||
}
|
||||
|
||||
// Close closes the database.
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// sqliteDSN enables WAL and a busy timeout. Kept local to match the
|
||||
// task and gateway stores; deduplicating the three copies is a
|
||||
// follow-up, not part of this change.
|
||||
func sqliteDSN(path string) string {
|
||||
separator := "?"
|
||||
if strings.HasSuffix(path, "?") || strings.HasSuffix(path, "&") {
|
||||
separator = ""
|
||||
} else if strings.Contains(path, "?") {
|
||||
separator = "&"
|
||||
}
|
||||
return path + separator + "_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
|
||||
}
|
||||
|
||||
func migrate(ctx context.Context, db *sql.DB) error {
|
||||
tx, err := db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var version int
|
||||
if err := tx.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version); err != nil {
|
||||
return err
|
||||
}
|
||||
if version > schemaVersion {
|
||||
return fmt.Errorf("config overlay schema version %d is newer than supported version %d", version, schemaVersion)
|
||||
}
|
||||
if version == schemaVersion {
|
||||
return tx.Commit()
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `PRAGMA user_version = 1`); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Set persists one override. key is a dotted config path
|
||||
// ("budgets.max_steps"); value is the JSON encoding of the field value
|
||||
// ("12", "\"60s\"", "true"). updatedBy names the writer for audit.
|
||||
// Keys in DeniedKeys are refused here as well as at the API layer.
|
||||
func (s *Store) Set(ctx context.Context, key, value, updatedBy string) error {
|
||||
if reason, denied := DeniedKeys[key]; denied {
|
||||
return fmt.Errorf("config key %s is not runtime-tunable: %s", key, reason)
|
||||
}
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`INSERT INTO config_overlay (key, value, updated_at, updated_by) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
value = excluded.value, updated_at = excluded.updated_at, updated_by = excluded.updated_by`,
|
||||
key, value, time.Now().UTC().Format(time.RFC3339), updatedBy)
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete removes one override, restoring the file's value for that key.
|
||||
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM config_overlay WHERE key = ?`, key)
|
||||
return err
|
||||
}
|
||||
|
||||
// Snapshot returns every stored override as a nested map of typed
|
||||
// values ready to decode into config.Config. Dotted keys are nested:
|
||||
// "budgets.max_steps" becomes map["budgets"]["max_steps"]. Values are
|
||||
// JSON-decoded so the caller never has to know the field's type.
|
||||
func (s *Store) Snapshot(ctx context.Context) (map[string]any, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT key, value FROM config_overlay`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
out := make(map[string]any)
|
||||
for rows.Next() {
|
||||
var key, raw string
|
||||
if err := rows.Scan(&key, &raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var value any
|
||||
if err := json.Unmarshal([]byte(raw), &value); err != nil {
|
||||
return nil, fmt.Errorf("overlay: key %s holds invalid JSON %q: %w", key, raw, err)
|
||||
}
|
||||
if err := Nest(out, key, value); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// Nest inserts value into root at the dotted key path ("a.b.c" ->
|
||||
// root["a"]["b"]["c"]), creating intermediate maps as needed.
|
||||
func Nest(root map[string]any, key string, value any) error {
|
||||
parts := strings.Split(key, ".")
|
||||
if len(parts) == 0 || parts[0] == "" {
|
||||
return fmt.Errorf("overlay: empty key %q", key)
|
||||
}
|
||||
cur := root
|
||||
for _, part := range parts[:len(parts)-1] {
|
||||
next, ok := cur[part].(map[string]any)
|
||||
if !ok {
|
||||
next = make(map[string]any)
|
||||
cur[part] = next
|
||||
}
|
||||
cur = next
|
||||
}
|
||||
cur[parts[len(parts)-1]] = value
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package overlay
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func openTest(t *testing.T) (*Store, context.Context) {
|
||||
t.Helper()
|
||||
s, err := Open(context.Background(), filepath.Join(t.TempDir(), "config.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s, context.Background()
|
||||
}
|
||||
|
||||
func TestSetGetSnapshotRoundTrip(t *testing.T) {
|
||||
s, ctx := openTest(t)
|
||||
|
||||
for _, tc := range []struct {
|
||||
key, value string
|
||||
}{
|
||||
{"budgets.max_steps", "12"},
|
||||
{"label", `"archie"`},
|
||||
{"containers.enabled", "true"},
|
||||
{"web.listen", `":8643"`},
|
||||
} {
|
||||
if err := s.Set(ctx, tc.key, tc.value, "test"); err != nil {
|
||||
t.Fatalf("Set(%s): %v", tc.key, err)
|
||||
}
|
||||
}
|
||||
|
||||
snap, err := s.Snapshot(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got := snap["budgets"].(map[string]any)["max_steps"]; !reflect.DeepEqual(got, float64(12)) {
|
||||
t.Errorf("budgets.max_steps = %#v, want float64(12)", got)
|
||||
}
|
||||
if got := snap["label"]; got != "archie" {
|
||||
t.Errorf("label = %#v, want archie", got)
|
||||
}
|
||||
if got := snap["containers"].(map[string]any)["enabled"]; got != true {
|
||||
t.Errorf("containers.enabled = %#v, want true", got)
|
||||
}
|
||||
if got := snap["web"].(map[string]any)["listen"]; got != ":8643" {
|
||||
t.Errorf("web.listen = %#v, want :8643", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetUpsertsAndDeleteRestores(t *testing.T) {
|
||||
s, ctx := openTest(t)
|
||||
|
||||
if err := s.Set(ctx, "label", `"first"`, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Set(ctx, "label", `"second"`, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap, err := s.Snapshot(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if snap["label"] != "second" {
|
||||
t.Fatalf("after upsert, label = %#v, want second", snap["label"])
|
||||
}
|
||||
|
||||
if err := s.Delete(ctx, "label"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snap, err = s.Snapshot(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(snap) != 0 {
|
||||
t.Fatalf("after delete, snapshot = %#v, want empty", snap)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetRefusesDeniedKeys(t *testing.T) {
|
||||
s, ctx := openTest(t)
|
||||
for key := range DeniedKeys {
|
||||
if err := s.Set(ctx, key, `"x"`, "test"); err == nil {
|
||||
t.Errorf("Set(%s) succeeded, want denial", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNestBuildsNestedMaps(t *testing.T) {
|
||||
root := map[string]any{}
|
||||
if err := Nest(root, "a.b.c", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := Nest(root, "a.b.d", "x"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ab := root["a"].(map[string]any)["b"].(map[string]any)
|
||||
if ab["c"] != 1 || ab["d"] != "x" {
|
||||
t.Fatalf("nested map = %#v", root)
|
||||
}
|
||||
if err := Nest(root, "", 1); err == nil {
|
||||
t.Fatal("empty key accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenIdempotentAndVersioned(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config.sqlite")
|
||||
s1, err := Open(context.Background(), path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = s1.Close()
|
||||
s2, err := Open(context.Background(), path)
|
||||
if err != nil {
|
||||
t.Fatalf("reopen: %v", err)
|
||||
}
|
||||
_ = s2.Close()
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,12 +1,31 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"maps"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/configuration/overlay"
|
||||
)
|
||||
|
||||
// Sentinel errors for handleConfigUpdate status classification. The
|
||||
// composition root wraps its UpdateConfig errors with these so the
|
||||
// handler can answer 400 (invalid input) or 503 (unavailable) without
|
||||
// reaching into infrastructure internals.
|
||||
var (
|
||||
// ErrConfigUpdateUnavailable reports that config editing is not
|
||||
// wired (no UpdateConfig seam, or the overlay is skipped by the
|
||||
// recovery flag).
|
||||
ErrConfigUpdateUnavailable = errors.New("config editing unavailable")
|
||||
// ErrConfigUpdateInvalid reports a rejected update: a denylisted
|
||||
// key, a failed validation of the materialised config, or an
|
||||
// unparseable value.
|
||||
ErrConfigUpdateInvalid = errors.New("config update invalid")
|
||||
)
|
||||
|
||||
// ChannelView is one conversational front-end as shown on the dashboard's
|
||||
@@ -40,7 +59,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),
|
||||
@@ -195,6 +214,17 @@ 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"`
|
||||
// Locked maps dotted config keys that cannot be changed from the
|
||||
// dashboard to the reason. The UI renders these rows disabled rather
|
||||
// than silently omitting the edit affordance.
|
||||
Locked map[string]string `json:"locked,omitempty"`
|
||||
// Overridden lists the dotted config keys currently set by the
|
||||
// runtime overlay, so the UI can mark those rows (their file value
|
||||
// is shadowed until reset) and offer a per-row reset.
|
||||
Overridden []string `json:"overridden,omitempty"`
|
||||
}
|
||||
|
||||
// IdentityView is who Archie is on the forge -- never the token that
|
||||
@@ -292,7 +322,16 @@ 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()
|
||||
|
||||
var provenance []ConfigOrigin
|
||||
if p := s.ConfigProvenance.Load(); p != nil {
|
||||
provenance = append([]ConfigOrigin(nil), (*p)...)
|
||||
}
|
||||
|
||||
view := ConfigView{
|
||||
Identity: IdentityView{
|
||||
@@ -334,12 +373,101 @@ 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,
|
||||
Locked: lockedConfigKeys(),
|
||||
}
|
||||
if s.ConfigOverrides != nil {
|
||||
if overridden, err := s.ConfigOverrides(r.Context()); err == nil {
|
||||
view.Overridden = overridden
|
||||
}
|
||||
// A failed read omits the list rather than failing the whole
|
||||
// view; the reload status carries the overlay degrade reason.
|
||||
}
|
||||
if s.LastReload != nil {
|
||||
rs := s.LastReload()
|
||||
view.Reload = &rs
|
||||
}
|
||||
|
||||
writeJSON(w, view)
|
||||
}
|
||||
|
||||
// handleConfigReset deletes one runtime-overlay row via ResetConfig,
|
||||
// restoring the file value for that key. The dashboard offers this on
|
||||
// overridden rows so it can remove an override it created.
|
||||
func (s *Server) handleConfigReset(w http.ResponseWriter, r *http.Request) {
|
||||
if s.ResetConfig == nil {
|
||||
http.Error(w, ErrConfigUpdateUnavailable.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if body.Key == "" {
|
||||
http.Error(w, "key required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.ResetConfig(r.Context(), body.Key); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, ErrConfigUpdateUnavailable):
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
case errors.Is(err, ErrConfigUpdateInvalid):
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
default:
|
||||
http.Error(w, "config reset failed: "+err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// lockedConfigKeys returns the dotted config keys the overlay refuses
|
||||
// to set, with the reason shown in the UI. These are the daemon's own
|
||||
// bootstrap inputs; changing them from the dashboard could break the
|
||||
// next boot.
|
||||
func lockedConfigKeys() map[string]string {
|
||||
out := make(map[string]string, len(overlay.DeniedKeys))
|
||||
maps.Copy(out, overlay.DeniedKeys)
|
||||
return out
|
||||
}
|
||||
|
||||
// handleConfigUpdate applies a set of dotted-path config updates via
|
||||
// UpdateConfig, which the composition root wires to the same
|
||||
// validate-persist-publish path as reload. The dashboard can then
|
||||
// change runtime-tunable settings without hand-editing TOML.
|
||||
func (s *Server) handleConfigUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
if s.UpdateConfig == nil {
|
||||
http.Error(w, ErrConfigUpdateUnavailable.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Updates map[string]any `json:"updates"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(body.Updates) == 0 {
|
||||
http.Error(w, "no updates provided", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := s.UpdateConfig(r.Context(), body.Updates); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, ErrConfigUpdateUnavailable):
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
case errors.Is(err, ErrConfigUpdateInvalid):
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
default:
|
||||
http.Error(w, "config update failed: "+err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
func reposView(repos []config.Repo) []RepoView {
|
||||
out := make([]RepoView, 0, len(repos))
|
||||
for _, r := range repos {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -23,8 +25,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 +60,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 +74,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 {
|
||||
@@ -146,6 +148,248 @@ 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigReportsLockedKeys proves the dashboard is told which
|
||||
// config keys it cannot edit and why, so it can disable those rows
|
||||
// instead of silently omitting the edit affordance.
|
||||
func TestHandleConfigReportsLockedKeys(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)
|
||||
}
|
||||
for _, key := range []string{"db_path", "work_dir"} {
|
||||
if got.Locked[key] == "" {
|
||||
t.Errorf("Locked[%q] is empty, want a reason", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigUpdateAppliesViaSeam proves the PATCH handler passes
|
||||
// the decoded updates to the wired UpdateConfig seam and answers ok.
|
||||
func TestHandleConfigUpdateAppliesViaSeam(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
var got map[string]any
|
||||
srv.UpdateConfig = func(_ context.Context, updates map[string]any) error {
|
||||
got = updates
|
||||
return nil
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config",
|
||||
strings.NewReader(`{"updates": {"budgets.max_steps": 12}}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if got["budgets.max_steps"] != float64(12) {
|
||||
t.Errorf("updates = %#v, want budgets.max_steps=12", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigUpdateInvalidMapsTo400 proves a rejected update (the
|
||||
// seam wraps its error with ErrConfigUpdateInvalid) answers 400.
|
||||
func TestHandleConfigUpdateInvalidMapsTo400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.UpdateConfig = func(context.Context, map[string]any) error {
|
||||
return fmt.Errorf("%w: label is not runtime-tunable", ErrConfigUpdateInvalid)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config",
|
||||
strings.NewReader(`{"updates": {"label": "x"}}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400, body = %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigUpdateUnavailableMapsTo503 proves a disabled overlay
|
||||
// (ErrConfigUpdateUnavailable) answers 503, as does a server with no
|
||||
// UpdateConfig seam at all.
|
||||
func TestHandleConfigUpdateUnavailableMapsTo503(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.UpdateConfig = func(context.Context, map[string]any) error {
|
||||
return fmt.Errorf("%w: overlay disabled by recovery flag", ErrConfigUpdateUnavailable)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config",
|
||||
strings.NewReader(`{"updates": {"label": "x"}}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503, body = %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleConfigUpdateWithoutSeamMapsTo503(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPatch, "/api/config",
|
||||
strings.NewReader(`{"updates": {"label": "x"}}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503, body = %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleConfigIncludesOverridden proves the overridden dotted keys
|
||||
// reach the view so the UI can mark rows shadowed by the runtime overlay.
|
||||
func TestHandleConfigIncludesOverridden(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
srv.ConfigOverrides = func(context.Context) ([]string, error) {
|
||||
return []string{"budgets.max_steps", "label"}, nil
|
||||
}
|
||||
|
||||
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.Overridden) != 2 || got.Overridden[0] != "budgets.max_steps" || got.Overridden[1] != "label" {
|
||||
t.Errorf("Overridden = %v, want [budgets.max_steps label]", got.Overridden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleConfigResetCallsSeamAndAnswersOk(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
var got string
|
||||
srv.ResetConfig = func(_ context.Context, key string) error {
|
||||
got = key
|
||||
return nil
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/config/reset",
|
||||
strings.NewReader(`{"key": "budgets.max_steps"}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
if got != "budgets.max_steps" {
|
||||
t.Errorf("ResetConfig called with %q, want budgets.max_steps", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleConfigResetWithoutSeamMapsTo503(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/config/reset",
|
||||
strings.NewReader(`{"key": "label"}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503, body = %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleConfigResetRejectsEmptyKey(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.ResetConfig = func(context.Context, string) error { return nil }
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/config/reset",
|
||||
strings.NewReader(`{"key": ""}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400, body = %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleChannelsReportsConfiguredState(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
srv.Cfg = configWithFakeSecrets()
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) != ""
|
||||
}
|
||||
@@ -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),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/channels"
|
||||
@@ -32,8 +33,16 @@ 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.
|
||||
//
|
||||
// In production this is the daemon's OWN Holder (main.go wires
|
||||
// web.Cfg = d.Cfg), so Set here publishes to the running daemon. A
|
||||
// config-mutating handler must never call Set directly: it goes
|
||||
// through the same path as reload -- apply to a copy, validate the
|
||||
// materialised config, persist, then Set.
|
||||
Cfg *config.Holder
|
||||
|
||||
// Workflows is the executable registry snapshot supplied by composition.
|
||||
Workflows []workflow.Definition
|
||||
@@ -48,9 +57,38 @@ 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
|
||||
|
||||
// UpdateConfig applies a set of dotted-path config updates through
|
||||
// the same validate-persist-publish path as reload (wired by the
|
||||
// composition root). Optional: when nil, PATCH /api/config answers
|
||||
// 503. The handler never touches the Cfg Holder directly -- see the
|
||||
// Cfg field doc.
|
||||
UpdateConfig func(context.Context, map[string]any) error
|
||||
|
||||
// ConfigOverrides lists the dotted config keys currently overridden
|
||||
// by the runtime overlay, so the dashboard can mark those rows and
|
||||
// offer a reset. Optional: when nil, the /api/config response omits
|
||||
// the overridden list.
|
||||
ConfigOverrides func(context.Context) ([]string, error)
|
||||
|
||||
// ResetConfig deletes one runtime-overlay row and republishes file +
|
||||
// remaining overlay. Optional: when nil, POST /api/config/reset
|
||||
// answers 503. Like UpdateConfig, it never touches the Cfg Holder
|
||||
// directly.
|
||||
ResetConfig func(context.Context, string) error
|
||||
|
||||
// Channels reports actual adapter lifecycle, independently of configuration
|
||||
// presence. Nil preserves the configuration-only fallback for tests and
|
||||
@@ -103,6 +141,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
|
||||
@@ -145,6 +188,8 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/channels", s.handleChannels)
|
||||
mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload)
|
||||
mux.HandleFunc("GET /api/config", s.handleConfig)
|
||||
mux.HandleFunc("PATCH /api/config", s.handleConfigUpdate)
|
||||
mux.HandleFunc("POST /api/config/reset", s.handleConfigReset)
|
||||
mux.HandleFunc("GET /api/logs", s.handleLogs)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs)
|
||||
mux.HandleFunc("GET /api/logs/stream", s.handleLogStream)
|
||||
|
||||
Vendored
+6
-6
@@ -1,12 +1,12 @@
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:`<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>`,chat:`<path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v7a2.5 2.5 0 0 1-2.5 2.5H11l-4.5 4v-4.1A2.5 2.5 0 0 1 4 12.5z"/><path d="M8 8h8M8 11h5"/>`,tasks:`<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>`,logs:`<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>`,skills:`<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>`,workflows:`<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>`,memory:`<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>`,channels:`<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>`,settings:`<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>`,search:`<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>`,moon:`<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>`,sun:`<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>`,refresh:`<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>`,bell:`<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>`,trendUp:`<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>`,trendDown:`<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>`,check:`<path d="M4.5 12.5l5 5 10-11"/>`,help:`<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>`};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},siLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=`<polyline points="${l}" fill="none" stroke="${n}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{widt
Line truncated
|
||||
<path d="${l(150,240)}" fill="none" stroke="var(--border)"
|
||||
stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="${l(150,240)}" fill="none" stroke="${a}"
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${c}"
|
||||
stroke-dashoffset="${c*(1-i/100)}"
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function
Line truncated
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function
Line truncated
|
||||
<div class="chat-page-content">
|
||||
<header class="chat-topbar">
|
||||
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
|
||||
@@ -71,10 +71,10 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;function Ae(){let e=document.createElement(`template`);e.innerHTML=ke.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function je(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`;function Ne(){let e=document.createElement(`template`);e.innerHTML=Me.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i<t.length&&n.append(document.createTextNode(t.slice(i))),n}function Pe(t){let n=e(`div.chat-bubble-text`),r=String(t||``).split(`
|
||||
`),i=[],a=null,o=null,s=()=>{i.length&&(n.append(e(`p`,J(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;t<r.length;t++){let l=r[t];if(l.startsWith("```")){s(),c(),o?(n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1<r.length?Y(r[t+1]):null;if(u&&d&&Me(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=Y(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Me(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Ne(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Pe(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?je(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=je(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var Fe=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Fe);return e||(e=crypto.randomUUID(),localStorage.setItem(Fe,e)),e}function Ie(e){return{text:e,sourceID:crypto.randomUUID()}}function Le(e){return{...e}}function Re(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Le(e.turn):Ie(r),isRetry:n}}function ze({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Ne(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function Be(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,Ve(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function Ve(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function He(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Ue(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function We(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function Ge(e){return e?.status===501?null:`Could not check for updates.`}function Ke(){let{root:t,refs:n}=Ae(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Pe(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function
Line truncated
|
||||
`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1<r.length?Y(r[t+1]):null;if(u&&d&&Fe(d)&&u.length===d.length){s(),c();let i=[];for(t+=2;t<r.length;t++){let e=Y(r[t]);if(!e||e.length!==u.length){t--;break}i.push(e)}let a=e(`tbody`);for(let t of i)a.append(e(`tr`,...t.map(t=>e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(`
|
||||
`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Fe(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Ie(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Le(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Pe(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Pe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}var Re=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(Re);return e||(e=crypto.randomUUID(),localStorage.setItem(Re,e)),e}function ze(e){return{text:e,sourceID:crypto.randomUUID()}}function Be(e){return{...e}}function Ve(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Be(e.turn):ze(r),isRetry:n}}function He({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Ie(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function Ue(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,We(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function We(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function Ge(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function Ke(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function qe(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function Je(e){return e?.status===501?null:`Could not check for updates.`}function Ye(){let{root:t,refs:n}=Ne(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(Le(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function
Line truncated
|
||||
|
||||
`);i=a.pop()||``;for(let e of a){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=Le(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{Ve({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:Ke},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:ye},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ee},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:ie}],qe=`archie.theme`;function Je(e){document.documentElement.dataset.theme=e,localStorage.setItem(qe,e)}function $(){return localStorage.getItem(qe)||`dark`}function Ye(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Je($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function Xe(){Je($());let t=e(`main.main`),r=Ye(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Ze(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.has
Line truncated
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=Be(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{We({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:Ye},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:Se},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:ke},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:ie}],Xe=`archie.theme`;function Ze(e){document.documentElement.dataset.theme=e,localStorage.setItem(Xe,e)}function $(){return localStorage.getItem(Xe)||`dark`}function Qe(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Ze($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function $e(){Ze($());let t=e(`main.main`),r=Qe(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):et(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.has
Line truncated
|
||||
@@ -86,6 +86,26 @@ export const api = {
|
||||
return res.json();
|
||||
},
|
||||
config: () => req("/api/config"),
|
||||
configUpdate: async (updates) => {
|
||||
const res = await fetch("/api/config", {
|
||||
method: "PATCH",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
|
||||
body: JSON.stringify({ updates }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res.json();
|
||||
},
|
||||
configReset: async (key) => {
|
||||
const res = await fetch("/api/config/reset", {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json", "X-Archie-CSRF": "1" },
|
||||
body: JSON.stringify({ key }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res.json();
|
||||
},
|
||||
logs: (params) => req("/api/logs" + qs(params)),
|
||||
memory: () => req("/api/memory"),
|
||||
chatSessions: () => req("/api/chat/sessions"),
|
||||
|
||||
@@ -58,3 +58,111 @@
|
||||
color: var(--fg);
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* Inline edit affordance: value + Edit on the right, input + Save /
|
||||
Cancel while editing, and the server's reason for locked rows. */
|
||||
.cfg-value-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: var(--sp-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cfg-edit {
|
||||
font: inherit;
|
||||
font-size: var(--text-xs);
|
||||
color: var(--fg-muted);
|
||||
background: var(--surface-hover);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: 2px var(--sp-2);
|
||||
cursor: pointer;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.cfg-edit:hover {
|
||||
color: var(--fg);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.cfg-editing {
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.cfg-input {
|
||||
font: inherit;
|
||||
font-size: var(--text-xs);
|
||||
color: var(--fg);
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
min-width: 0;
|
||||
flex: 1 1 10rem;
|
||||
}
|
||||
|
||||
.cfg-input:focus {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.cfg-save,
|
||||
.cfg-cancel {
|
||||
font: inherit;
|
||||
font-size: var(--text-xs);
|
||||
border-radius: var(--radius-sm);
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
cursor: pointer;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.cfg-save {
|
||||
background: var(--accent);
|
||||
border: 1px solid var(--accent);
|
||||
color: var(--accent-fg);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.cfg-save:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.cfg-cancel {
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-strong);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.cfg-cancel:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.cfg-locked {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--fg-subtle);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.cfg-overridden {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.cfg-notice {
|
||||
border-left: 3px solid var(--warn);
|
||||
}
|
||||
|
||||
.cfg-notice p {
|
||||
margin: 0;
|
||||
font-size: var(--text-sm);
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.cfg-error {
|
||||
font-size: var(--text-xs);
|
||||
color: var(--danger);
|
||||
flex-basis: 100%;
|
||||
text-align: right;
|
||||
}
|
||||
+174
-44
@@ -3,11 +3,18 @@ import { api } from "../base/api.js";
|
||||
import { el, empty, mount, pill } from "../base/dom.js";
|
||||
|
||||
/**
|
||||
* A read-only view of the config archied is actually running with, grouped
|
||||
* by domain and explained in plain language. Backed by GET /api/config,
|
||||
* A view of the config archied is actually running with, grouped by
|
||||
* domain and explained in plain language. Backed by GET /api/config,
|
||||
* which is built from an explicit, hand-picked allowlist on the Go side
|
||||
* (internal/webui/api_config.go handleConfig) -- secrets never reach this
|
||||
* page, so nothing here needs to be hidden or redacted client-side.
|
||||
* (internal/webui/api_config.go handleConfig) -- secrets never reach
|
||||
* this page, so nothing here needs to be hidden or redacted client-side.
|
||||
*
|
||||
* Scalar rows that are not denylisted are editable inline: Edit swaps
|
||||
* the value for an input, Save PATCHes the dotted key to /api/config,
|
||||
* which validates the materialised config before persisting to the
|
||||
* runtime overlay and republishing. Structured values (repositories,
|
||||
* models, providers -- arrays and maps) render read-only; denylisted
|
||||
* keys (db_path, work_dir) render disabled with the server's reason.
|
||||
*/
|
||||
export function settingsPage() {
|
||||
const root = el("div");
|
||||
@@ -35,13 +42,13 @@ export function settingsPage() {
|
||||
async function load() {
|
||||
try {
|
||||
const cfg = await api.config();
|
||||
renderBody(cfg);
|
||||
renderBody(cfg, load);
|
||||
} catch (err) {
|
||||
mount(body, el("div.card", empty("Cannot reach archied", String(err.message || err))));
|
||||
}
|
||||
}
|
||||
|
||||
function renderBody(cfg) {
|
||||
function renderBody(cfg, reload) {
|
||||
if (!cfg || Object.keys(cfg).length === 0) {
|
||||
mount(
|
||||
body,
|
||||
@@ -56,16 +63,24 @@ export function settingsPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const ctx = { locked: cfg.locked || {}, overridden: cfg.overridden || [], onSaved: reload };
|
||||
const banners = [
|
||||
cfg.reload?.overlay_unavailable &&
|
||||
el("div.card.cfg-notice", el("p", `The runtime config overlay is not in effect: ${cfg.reload.overlay_unavailable}`)),
|
||||
cfg.reload?.last_error &&
|
||||
el("div.card.cfg-notice", el("p", `The last config reload failed; the running config is unchanged: ${cfg.reload.last_error}`)),
|
||||
];
|
||||
mount(
|
||||
body,
|
||||
identityCard(cfg.identity),
|
||||
...banners,
|
||||
identityCard(cfg.identity, ctx),
|
||||
repositoriesCard(cfg.repositories),
|
||||
modelsAndProvidersCard(cfg.models, cfg.providers),
|
||||
budgetsCard(cfg.budgets),
|
||||
agentCard(cfg.agent),
|
||||
storageCard(cfg.storage, cfg.containers),
|
||||
webCard(cfg.web),
|
||||
provenanceCard(cfg.provenance),
|
||||
budgetsCard(cfg.budgets, ctx),
|
||||
agentCard(cfg.agent, ctx),
|
||||
storageCard(cfg.storage, cfg.containers, ctx),
|
||||
webCard(cfg.web, ctx),
|
||||
provenanceCard(cfg.provenance),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,23 +104,138 @@ function section(title, sub, ...children) {
|
||||
);
|
||||
}
|
||||
|
||||
function row(label, value) {
|
||||
return el("div.cfg-row", el("span.cfg-label", label), el("span.cfg-value.mono", value ?? "—"));
|
||||
// row renders one label/value pair. opts.key makes it editable via a
|
||||
// PATCH to /api/config; opts.locked[key] disables it with the server's
|
||||
// reason; opts.overridden marks a key whose file value is shadowed by
|
||||
// the runtime overlay and offers a reset; no key means a plain read-only
|
||||
// row (structured values and provenance).
|
||||
function row(label, value, opts) {
|
||||
const labelEl = el("span.cfg-label", label);
|
||||
if (!opts?.key) {
|
||||
return el("div.cfg-row", labelEl, el("span.cfg-value.mono", value ?? "—"));
|
||||
}
|
||||
if (opts.locked?.[opts.key]) {
|
||||
return el(
|
||||
"div.cfg-row",
|
||||
labelEl,
|
||||
el(
|
||||
"div.cfg-value-cell",
|
||||
el("span.cfg-value.mono", value ?? "—"),
|
||||
el("span.cfg-locked", opts.locked[opts.key]),
|
||||
),
|
||||
);
|
||||
}
|
||||
const display = el("span.cfg-value.mono", value ?? "—");
|
||||
const editBtn = el("button.cfg-edit", { title: `Edit ${label}` }, "Edit");
|
||||
const overridden = opts.overridden?.includes(opts.key);
|
||||
const cell = el(
|
||||
"div.cfg-value-cell",
|
||||
display,
|
||||
overridden && el("span.cfg-overridden", { title: "Set via the dashboard; edit the file, then reset" }, "overridden"),
|
||||
editBtn,
|
||||
overridden && el("button.cfg-edit", { title: "Reset to the file value" }, "Reset"),
|
||||
);
|
||||
const rowEl = el("div.cfg-row", labelEl, cell);
|
||||
editBtn.addEventListener("click", () => startEdit(rowEl, cell, label, opts));
|
||||
if (overridden) {
|
||||
const resetBtn = cell.lastChild;
|
||||
resetBtn.addEventListener("click", () => resetOverride(resetBtn, opts));
|
||||
}
|
||||
return rowEl;
|
||||
}
|
||||
|
||||
function identityCard(identity) {
|
||||
// resetOverride deletes one runtime-overlay row via the reset seam, then
|
||||
// re-renders so the row returns to its file value. Errors show inline in
|
||||
// the row's marker slot.
|
||||
function resetOverride(btn, opts) {
|
||||
const { key, onSaved } = opts;
|
||||
const marker = btn.parentElement.querySelector(".cfg-overridden");
|
||||
btn.disabled = true;
|
||||
api
|
||||
.configReset(key)
|
||||
.then(() => onSaved?.())
|
||||
.catch((err) => {
|
||||
btn.disabled = false;
|
||||
if (marker) {
|
||||
marker.textContent = String(err.message || err);
|
||||
marker.classList.add("cfg-error");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function startEdit(rowEl, cell, label, opts) {
|
||||
const { key, type, raw, onSaved } = opts;
|
||||
const input = type === "bool"
|
||||
? el(
|
||||
"select.cfg-input",
|
||||
el("option", { value: "true", selected: raw === true }, "true"),
|
||||
el("option", { value: "false", selected: raw === false }, "false"),
|
||||
)
|
||||
: el("input.cfg-input", { type: "text", value: String(raw ?? "") });
|
||||
const save = el("button.cfg-save", { type: "button" }, "Save");
|
||||
const cancel = el("button.cfg-cancel", { type: "button" }, "Cancel");
|
||||
const error = el("span.cfg-error");
|
||||
const editing = el("div.cfg-value-cell.cfg-editing", input, save, cancel, error);
|
||||
rowEl.replaceChild(editing, cell);
|
||||
input.focus();
|
||||
|
||||
const done = () => rowEl.replaceChild(cell, editing);
|
||||
cancel.addEventListener("click", done);
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") save.click();
|
||||
if (e.key === "Escape") done();
|
||||
});
|
||||
|
||||
save.addEventListener("click", async () => {
|
||||
const parsed = parseEdit(type, input.value);
|
||||
if (parsed.error) {
|
||||
error.textContent = parsed.error;
|
||||
return;
|
||||
}
|
||||
save.disabled = true;
|
||||
try {
|
||||
await api.configUpdate({ [key]: parsed.value });
|
||||
onSaved?.();
|
||||
} catch (err) {
|
||||
// The server's reason (validation failure, denylisted key) is the
|
||||
// part the operator can act on; show it instead of the status.
|
||||
error.textContent = String(err.message || err);
|
||||
save.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// parseEdit converts the input text to the JSON type the config field
|
||||
// expects. Durations and strings pass through (the server validates
|
||||
// duration syntax); ints are parsed client-side so a typo fails before
|
||||
// a round trip.
|
||||
function parseEdit(type, text) {
|
||||
switch (type) {
|
||||
case "int": {
|
||||
const n = parseInt(text, 10);
|
||||
if (Number.isNaN(n)) return { error: "Enter a whole number" };
|
||||
return { value: n };
|
||||
}
|
||||
case "bool":
|
||||
return { value: text === "true" };
|
||||
default:
|
||||
return { value: text };
|
||||
}
|
||||
}
|
||||
|
||||
function identityCard(identity, ctx) {
|
||||
if (!identity) return section("Identity", "Who Archie is on the forge.", empty("Not available"));
|
||||
return section(
|
||||
"Identity",
|
||||
"Who Archie is on the forge, and how it addresses commits and comments.",
|
||||
el(
|
||||
"div.cfg-rows",
|
||||
row("Bot account", identity.bot_user),
|
||||
row("Commit author email", identity.bot_email),
|
||||
row("Pickup label", identity.label),
|
||||
row("Forge type", identity.forge_type),
|
||||
row("Forge host", identity.forge_host),
|
||||
row("Max diff size (lines)", identity.diff_cap_lines),
|
||||
row("Bot account", identity.bot_user, { key: "bot_user", type: "string", raw: identity.bot_user, ...ctx }),
|
||||
row("Commit author email", identity.bot_email, { key: "bot_email", type: "string", raw: identity.bot_email, ...ctx }),
|
||||
row("Pickup label", identity.label, { key: "label", type: "string", raw: identity.label, ...ctx }),
|
||||
row("Forge type", identity.forge_type, { key: "forge.type", type: "string", raw: identity.forge_type, ...ctx }),
|
||||
row("Forge host", identity.forge_host, { key: "forge.host", type: "string", raw: identity.forge_host, ...ctx }),
|
||||
row("Max diff size (lines)", identity.diff_cap_lines || "Unlimited", { key: "diff_cap_lines", type: "int", raw: identity.diff_cap_lines, ...ctx }),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -198,30 +328,30 @@ function roleLabel(role) {
|
||||
return role.charAt(0).toUpperCase() + role.slice(1).replace(/_/g, " ");
|
||||
}
|
||||
|
||||
function budgetsCard(budgets) {
|
||||
function budgetsCard(budgets, ctx) {
|
||||
if (!budgets) return section("Budgets", "Limits on every agent stage.", empty("Not available"));
|
||||
return section(
|
||||
"Budgets",
|
||||
"The limits every autonomous stage runs under, so a stuck task cannot run forever.",
|
||||
el(
|
||||
"div.cfg-rows",
|
||||
row("Max steps", budgets.max_steps || "Unlimited"),
|
||||
row("Max tokens", budgets.max_tokens || "Unlimited"),
|
||||
row("Wall clock", budgets.wall_clock),
|
||||
row("Max gate failures before parking", budgets.gate_max_failures || "Unlimited"),
|
||||
row("Max steps", budgets.max_steps || "Unlimited", { key: "budgets.max_steps", type: "int", raw: budgets.max_steps, ...ctx }),
|
||||
row("Max tokens", budgets.max_tokens || "Unlimited", { key: "budgets.max_tokens", type: "int", raw: budgets.max_tokens, ...ctx }),
|
||||
row("Wall clock", budgets.wall_clock, { key: "budgets.wall_clock", type: "string", raw: budgets.wall_clock, ...ctx }),
|
||||
row("Max gate failures before parking", budgets.gate_max_failures || "Unlimited", { key: "budgets.gate_max_failures", type: "int", raw: budgets.gate_max_failures, ...ctx }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function agentCard(agent) {
|
||||
function agentCard(agent, ctx) {
|
||||
if (!agent) return section("Agent execution", "How Archie runs autonomous stages.", empty("Not available"));
|
||||
return section(
|
||||
"Agent execution",
|
||||
"How archied actually runs a stage of work.",
|
||||
el(
|
||||
"div.cfg-rows",
|
||||
row("Execution mode", agentModeLabel(agent.mode)),
|
||||
row("Worker command", agent.command),
|
||||
row("Execution mode", agentModeLabel(agent.mode), { key: "agent.mode", type: "string", raw: agent.mode, ...ctx }),
|
||||
row("Worker command", agent.command, { key: "agent.command", type: "string", raw: agent.command, ...ctx }),
|
||||
row("Extra environment variables passed through", agent.env?.length ? agent.env.join(", ") : "None"),
|
||||
),
|
||||
);
|
||||
@@ -240,18 +370,18 @@ function agentModeLabel(mode) {
|
||||
}
|
||||
}
|
||||
|
||||
function storageCard(storage, containers) {
|
||||
function storageCard(storage, containers, ctx) {
|
||||
const children = [];
|
||||
if (storage) {
|
||||
children.push(
|
||||
el("h3.cfg-subhead", "Paths"),
|
||||
el(
|
||||
"div.cfg-rows",
|
||||
row("Work directory", storage.work_dir),
|
||||
row("State path prefix", storage.db_path),
|
||||
row("Shared skills directory", storage.skills_dir || "None (uses the work directory)"),
|
||||
row("Daemon plugin directory", storage.plugin_dir || "None"),
|
||||
row("Secret engine plugin directory", storage.secret_engine_dir || "None (built-in engines only)"),
|
||||
row("Work directory", storage.work_dir, { key: "work_dir", type: "string", ...ctx }),
|
||||
row("State path prefix", storage.db_path, { key: "db_path", type: "string", ...ctx }),
|
||||
row("Shared skills directory", storage.skills_dir || "None (uses the work directory)", { key: "skills_dir", type: "string", raw: storage.skills_dir, ...ctx }),
|
||||
row("Daemon plugin directory", storage.plugin_dir || "None", { key: "plugin_dir", type: "string", raw: storage.plugin_dir, ...ctx }),
|
||||
row("Secret engine plugin directory", storage.secret_engine_dir || "None (built-in engines only)", { key: "secret_engine_dir", type: "string", raw: storage.secret_engine_dir, ...ctx }),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -260,13 +390,13 @@ function storageCard(storage, containers) {
|
||||
el("h3.cfg-subhead", "Sandboxed containers"),
|
||||
el(
|
||||
"div.cfg-rows",
|
||||
row("Sandboxing enabled", containers.enabled ? "Yes" : "No"),
|
||||
row("Agent image", containers.image || "Not set"),
|
||||
row("Max concurrent tasks", containers.max_concurrency || "Unlimited"),
|
||||
row("Container max lifetime", containers.max_uptime),
|
||||
row("Persistent volume retention", containers.volume_ttl),
|
||||
row("How images are refreshed", pullPolicyLabel(containers.pull_policy)),
|
||||
row("Docker network", containers.network || "Auto-detected"),
|
||||
row("Sandboxing enabled", containers.enabled ? "Yes" : "No", { key: "containers.enabled", type: "bool", raw: containers.enabled, ...ctx }),
|
||||
row("Agent image", containers.image || "Not set", { key: "containers.image", type: "string", raw: containers.image, ...ctx }),
|
||||
row("Max concurrent tasks", containers.max_concurrency || "Unlimited", { key: "containers.max_concurrency", type: "int", raw: containers.max_concurrency, ...ctx }),
|
||||
row("Container max lifetime", containers.max_uptime, { key: "containers.max_uptime", type: "string", raw: containers.max_uptime, ...ctx }),
|
||||
row("Persistent volume retention", containers.volume_ttl, { key: "containers.volume_ttl", type: "string", raw: containers.volume_ttl, ...ctx }),
|
||||
row("How images are refreshed", pullPolicyLabel(containers.pull_policy), { key: "containers.pull_policy", type: "string", raw: containers.pull_policy, ...ctx }),
|
||||
row("Docker network", containers.network || "Auto-detected", { key: "containers.network", type: "string", raw: containers.network, ...ctx }),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -279,11 +409,11 @@ function pullPolicyLabel(policy) {
|
||||
return "Only pull when the image is missing locally";
|
||||
}
|
||||
|
||||
function webCard(web) {
|
||||
function webCard(web, ctx) {
|
||||
if (!web) return section("Dashboard", "This dashboard's own listen address.", empty("Not available"));
|
||||
return section(
|
||||
"Dashboard",
|
||||
"This dashboard's own listen address.",
|
||||
el("div.cfg-rows", row("Listen address", web.listen === "off" ? "Disabled" : web.listen)),
|
||||
el("div.cfg-rows", row("Listen address", web.listen === "off" ? "Disabled" : web.listen, { key: "web.listen", type: "string", raw: web.listen === "off" ? "" : web.listen, ...ctx })),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user