Files
archie/internal/infrastructure/configuration/overlay/overlay.go
T
sam 03afd2e8ad refactor(webui): take configuration off the dashboard server
webui.Server declared Cfg *config.Holder with eight read sites, none of
which ran in the UI process: composition leaves it nil there. The field
survived because the daemon kept a webui.Server it never served, using it
to render the published ConfigView snapshot and to hold the readiness
probes (archie-core-ml30).

Split at the producer. LocalConfigView becomes webui.BuildConfigView, a
pure function over a ConfigViewInput the configuration owner assembles;
the DTO and its schema stay where the UI renders them. The daemon builds
that input from its own state (boot.configViewInput) and publishes the
result. Readiness reads the daemon's Holder, channel manager and chat
contract, and the registry it produces is a daemon field, not a field on
a server with no listener. Boot now owns one Holder instead of seeding a
second and replacing it in buildDaemon; operator retry caps read it too,
so they follow a reload rather than a boot-time snapshot.

Server loses Cfg, ConfigProvenance, LastReload, ConfigOverrides and
SetProvenance. The nil-guarded branches they fed went with them, each
checked first against what the UI process actually serves:

- chat.show_tool_calls and the /api/setup checklist were degraded, not
  dead. ConfigView gains a chat section carrying show_tool_calls, the
  operator name and whether a channel is configured, and both surfaces
  read the projection. The end-to-end suite asserts the checklist renders
  from the published snapshot.
- /api/logs takes its path as a process-local option. The history is on
  the daemon's disk, so a dashboard elsewhere cannot read it by learning
  the path; that route still needs a contract.
- handleChannels drops its config-derived fallback, superseded by the
  status manager, which already carries the descriptions and detail.
- trustForwardedHeaders keeps only the process's own setting, which the
  UI process already sets.
- resolveForge keeps the published-projection path it already had.

ConfigView.Editable moves to handleConfig, decided by whether this
process holds UpdateConfig. It describes the writer, not the document, so
the write contract (archie-core-j28m) makes the page editable by wiring
one field. The write handlers and their seams stay for it.

overlay.Store gains Keys: Snapshot nests dotted keys for decoding, so the
overridden-key list was publishing section names ("budgets") where the
dashboard marks and resets rows by stored key ("budgets.max_steps").

Multi-identity forge links move to archie-core-pv6t: forgeConfigForTask
resolved a task's forge from config.Config, had no reachable caller once
the holder was gone, and belongs in the projection rather than the
rendering package.
2026-09-11 23:57:38 +10:00

198 lines
6.2 KiB
Go

// 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"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
// DeniedKeys moved to internal/infrastructure/configuration ( DeniedKeys):
// webui references the constant and must not link this package's SQLite
// store (archie-core-8cda.5.6).
var DeniedKeys = configuration.DeniedKeys
// 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
}
// Keys lists the dotted keys the overlay sets, in sorted order. Snapshot
// nests them into a config-shaped map for decoding, which loses the paths --
// "budgets.max_steps" becomes out["budgets"]["max_steps"] and ranging over
// that map yields "budgets". The dashboard marks overridden rows and offers a
// per-row reset by dotted key, so it needs the keys as stored.
func (s *Store) Keys(ctx context.Context) ([]string, error) {
rows, err := s.db.QueryContext(ctx, `SELECT key FROM config_overlay ORDER BY key`)
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
var keys []string
for rows.Next() {
var key string
if err := rows.Scan(&key); err != nil {
return nil, err
}
keys = append(keys, key)
}
return keys, rows.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
}