From 1f05dbb33c87992d0e04fdafead1af27450bdf1d Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 24 Aug 2026 14:47:18 +1000 Subject: [PATCH] feat(deployment): default to managed NATS workers Autonomous workflows now always hand a complete task to a scoped archie-agent container. Embedded NATS is the default and external NATS changes only broker placement; legacy agent and containers.enabled inputs decode for migration but cannot select an execution path. The daemon flushes task-event subscriptions before a worker can publish, and runtime updates snapshot and restore the configured worker image. --- CLAUDE.md | 31 +++--- Dockerfile | 3 +- Taskfile.yml | 4 +- cmd/archied/bootstrap.go | 21 ++-- cmd/archied/execution_architecture_test.go | 24 ++++ cmd/archied/main.go | 26 ++--- cmd/archied/main_test.go | 10 ++ cmd/archied/reload.go | 4 +- cmd/archied/reload_test.go | 5 + config.example.toml | 33 ++---- deployment_contract_test.go | 105 ++++++++++++++++++ deployments/docker-nats-stack.toml | 8 +- deployments/local-ollama-standalone.toml | 4 - deployments/multi-forge-github-gitea.toml | 9 +- deployments/single-forge-github.toml | 9 +- deployments/systemd-user-service.md | 75 +++++++++---- docker-compose.yml | 16 +-- docs/architecture/configuration.md | 6 +- docs/prds/embedded-nats.md | 8 +- docs/prds/event-capture-storage.md | 19 ++-- install.sh | 25 +++-- internal/config/config.go | 15 ++- internal/daemon/daemon.go | 5 +- .../infrastructure/configuration/defaults.go | 13 +-- .../configuration/defaults_test.go | 20 +++- .../infrastructure/configuration/dir_test.go | 4 - .../configuration/loader_test.go | 24 ++++ .../configuration/overlay/overlay_test.go | 6 +- .../infrastructure/configuration/validate.go | 22 +--- .../configuration/validate_test.go | 12 +- internal/infrastructure/eventbus/nats/doc.go | 4 +- internal/releaseupdate/install_script_test.go | 75 +++++++++---- internal/webui/api_config.go | 2 - internal/webui/api_config_test.go | 9 ++ scripts/archie-update-install | 50 +++++++-- scripts/archie-update-watchdog | 20 +++- ui/dist/assets/index.js | 2 +- ui/src/settings/settings.js | 1 - 38 files changed, 497 insertions(+), 232 deletions(-) create mode 100644 cmd/archied/execution_architecture_test.go create mode 100644 deployment_contract_test.go diff --git a/CLAUDE.md b/CLAUDE.md index d437447d6..1bfb836dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -90,16 +90,17 @@ edit, find and grep are jailed to the configured workspace unless That setting is commented out in `config.example.toml` — an operator opt-in, not the default, and not an architectural requirement. Where the daemon runs and 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. +reach; neither is something the code should assume. `archied` and embedded NATS +run in the native daemon; per-task `archie-agent` workers run in Docker. **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.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. +`d.ConnectedNATS.URL`, captured at construction. That endpoint must therefore +be reachable from wherever the daemon runs *and* from inside the containers. +Embedded mode resolves the selected Docker bridge first and binds its +authenticated listener to that bridge's host gateway. External mode needs an +operator-supplied URL reachable from both; for the optional Compose broker that +is the pinned `172.19.0.1` gateway, not the service name and not localhost. 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 @@ -114,11 +115,12 @@ impossible regardless of what the config says or who reloads it; a reloaded daemon sends no credentials to the Docker API. Refresh the agent image explicitly instead: `docker compose pull agent`. -**`docker-compose.yml`** carries only NATS and the agent build stanza. The agent -has a `build` profile so `up -d` skips it — without the profile, compose creates -a container that exits 0 immediately and reports "Started", which reads as a -crash loop. `docker compose build agent` and `docker compose pull agent` still -work by name without activating the profile. +**`docker-compose.yml`** is optional in the default embedded deployment. It +carries an external NATS service plus the agent build stanza. The agent has a +`build` profile so `up -d nats` never starts it as a service — without the +profile, Compose creates a container that exits 0 immediately and reports +"Started", which reads as a crash loop. `docker compose build agent` and +`docker compose pull agent` work by name without activating the profile. **Config lives outside the repo**, at `${XDG_CONFIG_HOME:-~/.config}/archie/config.toml`. Nothing in the repo working @@ -162,8 +164,9 @@ read-only verification step. Run a single test: `go test ./internal/domain/workflow/... -run TestName -v`. -Docker/NATS stack: `task docker-build` (builds the agent image locally), -`task docker-up`, `task docker-down`, `task docker-logs`. +Docker helpers: `task docker-build` builds the agent image locally; +`task docker-up`, `task docker-down`, and `task docker-logs` manage the optional +external NATS service. ## Repository hygiene diff --git a/Dockerfile b/Dockerfile index 90ddf0814..92885d9bf 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,7 +3,8 @@ # Language packages are installed at runtime via uv/npm/go. # # Build: docker build -t archie-agent:latest . -# Run: docker run -e NATS_URL=nats://host:4222 archie-agent:latest +# This image is launched only by archied with a daemon-written task brief, +# task worktree mount, and authenticated NATS environment. # ── builder ─────────────────────────────────────────────────────────── FROM golang:1.26-trixie AS builder diff --git a/Taskfile.yml b/Taskfile.yml index a59cb3105..8929fa5a9 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -157,9 +157,9 @@ tasks: - docker compose build agent docker-up: - desc: Start the NATS service via docker compose + desc: Start the optional external NATS service via docker compose cmds: - - docker compose up -d + - docker compose up -d nats docker-down: desc: Stop the docker compose stack diff --git a/cmd/archied/bootstrap.go b/cmd/archied/bootstrap.go index 21a947387..e7a517b29 100644 --- a/cmd/archied/bootstrap.go +++ b/cmd/archied/bootstrap.go @@ -354,13 +354,9 @@ func (b *boot) setupObservability() { // connectNATS opens the NATS client. External mode dials cfg.NATS.URL; // embedded mode starts an in-process nats-server and dials it, so single- // process deployments get task distribution and reaction delivery without a -// separate server. Off mode returns nil and the SQLite ClaimNext flow runs. +// separate server. Broker deployment never changes the worker executor. func (b *boot) connectNATS(ctx context.Context) error { cfg, log := b.cfg, b.log - if cfg.NATS.Mode == config.NATSModeOff { - return nil - } - url := cfg.NATS.URL var natsToken string if cfg.NATS.Mode == config.NATSModeExternal { @@ -412,13 +408,10 @@ func (b *boot) connectNATS(ctx context.Context) error { return nil } -// setupContainers builds the optional container pool. Container setup -// degrades rather than aborting, for the same reason resolveForge does: -// containers are one capability among many, and refusing to start denies -// the operator chat, the dashboard and every other subsystem over a -// feature they may not be exercising right now. Under a systemd unit -// with Restart=on-failure it also turns a recoverable problem into a -// crash loop with the real error scrolling past unread. +// setupContainers builds the managed autonomous-worker pool. Failure degrades +// rather than aborting because the native interactive agent and dashboard do +// not require Docker; repository tasks park instead of falling back to a host +// model loop. func (b *boot) setupContainers(ctx context.Context) func() { containerPool, storeBackend, closeDocker := startContainers(ctx, b.cfg, b.log) b.containerPool = containerPool @@ -1251,8 +1244,8 @@ func (b *boot) startServices(ctx context.Context) error { return nil } -// setupBackends wires the optional runtime backends: the NATS client -// and the container pool. +// setupBackends wires the autonomous-workflow backends. Container setup may +// degrade, but NATS startup must succeed because there is no other task handoff. func (b *boot) setupBackends(ctx context.Context) error { closeContainers := b.setupContainers(ctx) err := b.connectNATS(ctx) diff --git a/cmd/archied/execution_architecture_test.go b/cmd/archied/execution_architecture_test.go new file mode 100644 index 000000000..03ca925e3 --- /dev/null +++ b/cmd/archied/execution_architecture_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "os" + "strings" + "testing" +) + +// Autonomous execution has one production composition: managed task +// containers over embedded or external NATS. These old switches must not +// quietly restore a host or no-broker path in the composition root. +func TestCompositionContainsNoAutonomousExecutionOptOut(t *testing.T) { + for _, file := range []string{"bootstrap.go", "main.go"} { + source, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + for _, forbidden := range []string{"NATSModeOff", "Containers.Enabled"} { + if strings.Contains(string(source), forbidden) { + t.Errorf("%s contains removed autonomous execution switch %q", file, forbidden) + } + } + } +} diff --git a/cmd/archied/main.go b/cmd/archied/main.go index be7e40efd..f4aa1b584 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -723,6 +723,12 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u if err != nil { return nil, err } + if err := nc.Flush(); err != nil { + if cleanupErr := sub.Unsubscribe(); cleanupErr != nil { + log.Warn("task event subscription cleanup failed after flush failure", "err", cleanupErr) + } + return nil, fmt.Errorf("flush task event subscription: %w", err) + } return func() { if err := sub.Unsubscribe(); err != nil { log.Warn("task event unsubscribe failed", "err", err) @@ -948,28 +954,22 @@ func memoryProvider(workDir string, log *slog.Logger) (*builtin.Provider, string return fb, fallback } -// startContainers brings up the container pool and storage backend, returning -// nils when containers are disabled or unavailable. +// startContainers brings up the mandatory autonomous-worker pool and storage +// backend, returning a degraded nil pool when Docker is unavailable. // -// Failure here degrades rather than aborting, for the same reason resolveForge -// does: containers are one capability among many, and refusing to start denies -// the operator chat, the dashboard and every other subsystem over a feature -// they may not be exercising. Under Restart=on-failure it also turns a -// recoverable problem into a crash loop with the real error scrolling past. +// Failure here degrades rather than aborting: the native interactive agent and +// dashboard remain useful without Docker, while autonomous tasks park because +// there is deliberately no host execution fallback. func startContainers( ctx context.Context, cfg config.Config, log *slog.Logger, ) (*container.Pool, storage.Backend, func()) { noop := func() {} - if !cfg.Containers.Enabled { - return nil, nil, noop - } - // Single Docker client shared between pool and storage backend. dockerCli, err := client.New(client.FromEnv) if err != nil { - log.Error("containers disabled: docker client unavailable", "err", err) + log.Error("autonomous workflows unavailable: docker client unavailable", "err", err) return nil, nil, noop } closeDocker := func() { @@ -991,7 +991,7 @@ func startContainers( // A missing image is recoverable by hand. The daemon sends no registry // credentials on pull (internal/container/pool.go), so a private // registry always needs the operator's CLI to fetch it first. - log.Error("containers disabled: pool unavailable", "err", err, + log.Error("autonomous workflows unavailable: container pool unavailable", "err", err, "hint", "run `docker compose pull agent` (or `build agent`) so the image is present locally") return nil, storage.NewDockerBackend(dockerCli), closeDocker } diff --git a/cmd/archied/main_test.go b/cmd/archied/main_test.go index d3744e972..227d3408b 100644 --- a/cmd/archied/main_test.go +++ b/cmd/archied/main_test.go @@ -1205,3 +1205,13 @@ func TestSubscribeAgentEventsDropsUnparseableMessages(t *testing.T) { }) } } + +func TestSubscribeAgentEventsFlushesBeforeReturning(t *testing.T) { + source, err := os.ReadFile("main.go") + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(source), "flush task event subscription") { + t.Fatal("subscribeAgentEvents does not flush its NATS subscription before returning") + } +} diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 409c9ef74..31f05aa4f 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -165,7 +165,7 @@ var reloadableFields = map[string]bool{ // 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, +// everything else in Containers (Image, 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 @@ -174,7 +174,7 @@ var reloadableFields = map[string]bool{ // forge client itself is startup-built, so Type/Token/TokenEnv stay // requires-restart. var reloadableSubFields = map[string]map[string]bool{ - "Containers": {"VolumeTTL": true}, + "Containers": {"LegacyEnabled": true, "VolumeTTL": true}, "Forge": {"Host": true}, } diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index 29b3e8037..6cdadbe73 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -219,6 +219,11 @@ func TestChangedNonReloadableFields(t *testing.T) { if got := changedNonReloadableFields(base, legacyOnly); len(got) != 0 { t.Fatalf("legacy agent change: got %v, want []", got) } + legacyContainers := base + legacyContainers.Containers.LegacyEnabled = true + if got := changedNonReloadableFields(base, legacyContainers); len(got) != 0 { + t.Fatalf("legacy containers.enabled change: got %v, want []", got) + } // Containers sub-field granularity: Image change warns, MaxConcurrency // and VolumeTTL changes do not. diff --git a/config.example.toml b/config.example.toml index 240f6dd29..dfac3ceb1 100644 --- a/config.example.toml +++ b/config.example.toml @@ -165,17 +165,6 @@ class = "ollama" # args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"] # work_dir = "/path/to/workspace" -[agent] -# How the daemon invokes the agent: -# "inprocess" – run agent logic directly in the daemon (default) -# "subprocess" – spawn `command` as a child, communicating over stdin/stdout -# "nats" – dispatch tasks over NATS (requires [nats]; add [containers] for Docker sandboxing) -mode = "inprocess" -# Binary to launch when mode = "subprocess". -command = "archie-agent" -# Environment variables forwarded to the agent process (subprocess/nats modes). -# env = ["GOCACHE"] - # Workspace code-search index. Paths default under work_dir when unset. [indexing] # Code-search index files (default: /indexes). @@ -228,15 +217,13 @@ max_steps = 60 wall_clock = "30m" gate_max_failures = 5 -# NATS JetStream for task distribution and reaction delivery. mode selects -# how NATS is provided: +# NATS is the sole autonomous workflow handoff. mode changes only where the +# broker runs; every workflow still runs in a managed task container: # "embedded" – in-process nats-server (the default; no external server) # "external" – connect to url -# "off" – no NATS; the SQLite ClaimNext flow is used for tasks -# Leave the section absent (or set no url) to run embedded; set mode="off" -# only to opt out of NATS entirely. +# Leave the section absent to run embedded. # [nats] -# mode = "embedded" # "embedded" | "external" | "off" +# mode = "embedded" # "embedded" | "external" # url = "nats://localhost:4222" # required when mode = "external" # token_env = "NATS_TOKEN" # optional external-server credential; embedded generates one per start @@ -255,12 +242,14 @@ gate_max_failures = 5 # rate_per_second = 1.0 # per-remote-address token bucket # rate_burst = 5 -# Docker sandbox execution of archie-agent. This is the only autonomous -# workflow execution path; embedded and external NATS are both supported. +# Docker sandbox execution of archie-agent is mandatory for autonomous +# workflows. Omit this section to use the default image, lifetimes, and pull +# policy; the options below show the available overrides. If Docker or +# the image is unavailable, chat and the dashboard still start while tasks +# park explicitly; archied never falls back to a host agent loop. # [containers] -# enabled = true -# image = "archie-agent:latest" # Docker image to run -# max_concurrency = 4 # max simultaneous tasks/containers +# image = "ghcr.io/samcharles93/archie-agent:latest" +# max_concurrency = 4 # optional cap; 0/absent means no global cap # max_uptime = "60m" # container lifetime cap # volume_ttl = "72h" # max age for persistent repo volumes and Git clone caches # pull_policy = "missing" # "missing" or "always" diff --git a/deployment_contract_test.go b/deployment_contract_test.go new file mode 100644 index 000000000..716267cef --- /dev/null +++ b/deployment_contract_test.go @@ -0,0 +1,105 @@ +package configtemplate + +import ( + "os" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" +) + +func readDeploymentFile(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +func TestExternalNATSProfileLoadsWithManagedWorkers(t *testing.T) { + doc, err := configuration.New(nil).File("deployments/docker-nats-stack.toml") + if err != nil { + t.Fatalf("load external NATS deployment: %v", err) + } + if doc.Config.NATS.Mode != config.NATSModeExternal { + t.Errorf("NATS mode = %q, want %q", doc.Config.NATS.Mode, config.NATSModeExternal) + } + if doc.Config.Containers.Image == "" { + t.Error("managed worker image is empty") + } + legacy := doc.Config.LegacyAgent + if legacy.Mode != "" || legacy.Command != "" || len(legacy.Env) != 0 { + t.Errorf("legacy agent selector decoded from supported profile: %#v", doc.Config.LegacyAgent) + } +} + +func TestInstallerUsesNativeDaemonAndManagedWorkerImage(t *testing.T) { + source := readDeploymentFile(t, "install.sh") + for _, forbidden := range []string{ + "[agent]", + `go build -o "${ARCHIE_BIN_DIR}/archie-agent"`, + `- archie-agent`, + "required only for NATS container mode", + } { + if strings.Contains(source, forbidden) { + t.Errorf("install.sh contains removed deployment behavior %q", forbidden) + } + } + for _, required := range []string{ + `ExecStart=${ARCHIE_BIN_DIR}/archied`, + "Docker is required for autonomous workflows", + } { + if !strings.Contains(source, required) { + t.Errorf("install.sh is missing deployment contract %q", required) + } + } +} + +func TestWorkerImageIsNotDocumentedAsAStandaloneExecutor(t *testing.T) { + source := readDeploymentFile(t, "Dockerfile") + if strings.Contains(source, "docker run -e NATS_URL") { + t.Error("Dockerfile documents an unsupported manually started worker") + } + if !strings.Contains(source, "launched only by archied") { + t.Error("Dockerfile does not state that archied owns worker lifecycle") + } +} + +func TestSupportedProfilesUseOneExecutionTopology(t *testing.T) { + profiles := []string{ + "deployments/single-forge-github.toml", + "deployments/multi-forge-github-gitea.toml", + "deployments/local-ollama-standalone.toml", + "deployments/docker-nats-stack.toml", + } + for _, path := range profiles { + source := readDeploymentFile(t, path) + if strings.Contains(source, "\n[agent]\n") { + t.Errorf("%s still selects a legacy agent executor", path) + } + } + + for _, path := range profiles[:2] { + source := readDeploymentFile(t, path) + for _, required := range []string{`mode = "embedded"`, "[containers]"} { + if !strings.Contains(source, required) { + t.Errorf("%s is missing default topology marker %q", path, required) + } + } + } + + external := readDeploymentFile(t, "deployments/docker-nats-stack.toml") + if !strings.Contains(external, `mode = "external"`) { + t.Error("docker-nats-stack.toml does not explicitly select external NATS") + } + + systemd := readDeploymentFile(t, "deployments/systemd-user-service.md") + if !strings.Contains(systemd, "Embedded NATS is the default") { + t.Error("systemd runbook does not identify embedded NATS as the default") + } + if strings.Contains(systemd, "still needs NATS") { + t.Error("systemd runbook still requires an external Compose NATS service") + } +} diff --git a/deployments/docker-nats-stack.toml b/deployments/docker-nats-stack.toml index dc7cc9709..9afb4e48d 100644 --- a/deployments/docker-nats-stack.toml +++ b/deployments/docker-nats-stack.toml @@ -38,19 +38,15 @@ parked = "agent:parked" # Stages run in sandboxed archie-agent containers over NATS. archied only # orchestrates: the agent image carries the toolchain and makes the model -# calls, so gate commands resolve there, not in the daemon image. Setting -# containers.enabled selects nats mode on its own, but pinning it here keeps -# the intent explicit. -[agent] -mode = "nats" +# calls, so gate commands resolve there, not in the native daemon. [nats] +mode = "external" # The pinned Compose-network gateway is reachable from both the host daemon # and the task containers it launches on archie-core_default. url = "nats://172.19.0.1:4222" [containers] -enabled = true network = "archie-core_default" image = "git.example.com/you/archie-agent:latest" max_concurrency = 4 diff --git a/deployments/local-ollama-standalone.toml b/deployments/local-ollama-standalone.toml index a24c21886..b94c8841f 100644 --- a/deployments/local-ollama-standalone.toml +++ b/deployments/local-ollama-standalone.toml @@ -31,10 +31,6 @@ models = [ "ollama/qwen2.5:7b" ] -[agent] -mode = "inprocess" -command = "archie-agent" - [budgets] max_steps = 60 wall_clock = "30m" diff --git a/deployments/multi-forge-github-gitea.toml b/deployments/multi-forge-github-gitea.toml index e10c1ec3d..55d80b100 100644 --- a/deployments/multi-forge-github-gitea.toml +++ b/deployments/multi-forge-github-gitea.toml @@ -19,9 +19,12 @@ builder = "openai/gpt-4o" class = "openai" api_key_env = "OPENAI_API_KEY" -[agent] -mode = "inprocess" -command = "archie-agent" +[nats] +mode = "embedded" + +[containers] +image = "ghcr.io/samcharles93/archie-agent:latest" +pull_policy = "missing" [budgets] max_steps = 60 diff --git a/deployments/single-forge-github.toml b/deployments/single-forge-github.toml index 533a8be97..0e48059fd 100644 --- a/deployments/single-forge-github.toml +++ b/deployments/single-forge-github.toml @@ -38,9 +38,12 @@ builder = "openai/gpt-4o" class = "openai" api_key_env = "OPENAI_API_KEY" -[agent] -mode = "inprocess" -command = "archie-agent" +[nats] +mode = "embedded" + +[containers] +image = "ghcr.io/samcharles93/archie-agent:latest" +pull_policy = "missing" [budgets] max_steps = 60 diff --git a/deployments/systemd-user-service.md b/deployments/systemd-user-service.md index 6a4afe039..34c678910 100644 --- a/deployments/systemd-user-service.md +++ b/deployments/systemd-user-service.md @@ -73,36 +73,71 @@ systemctl --user stop archied --- -## 4. Running Alongside the Docker Stack +## 4. Default: Native Daemon, Embedded NATS, Managed Containers -`archied` on the host still needs NATS and still spawns agent containers, so -`docker compose up -d` keeps running the bus and holds the network the agents -join. Two things bite in this hybrid layout: +Embedded NATS is the default. The systemd service runs `archied` natively, so +interactive chat keeps the host access the operator configured, while every +autonomous repository workflow runs in a task-scoped Docker container. No +Compose service or host `archie-agent` binary is required. -**One NATS URL serves two network namespaces.** The daemon hands agent -containers its own `nats.url` verbatim, so `nats://nats:4222` (resolvable only -inside compose) and `nats://127.0.0.1:4222` (the container's own loopback) are -both wrong. Use the compose network's gateway address, which the host and the -containers can both reach: +Docker must be installed and reachable by the service user. With no explicit +broker or container settings, Archie uses embedded NATS and the published +`ghcr.io/samcharles93/archie-agent:latest` image. An explicit equivalent is: ```toml [nats] -url = "nats://172.19.0.1:4222" +mode = "embedded" + +[containers] +image = "ghcr.io/samcharles93/archie-agent:latest" +pull_policy = "missing" ``` -`docker-compose.yml` pins the subnet so that address cannot drift when the -network is recreated. +At startup Archie resolves the Docker bridge used by its task containers, +binds the authenticated embedded broker only to that bridge's host gateway, +and passes the resulting endpoint to each worker. There is no port to publish +and no broker URL to maintain. -**`pull_policy` must be `"missing"` against a private registry.** The daemon -calls the Docker API with no registry credentials, so `"always"` gets a 401, -which fails the container pool and exits the daemon. Refresh the agent image -by hand instead: +If Docker or the image is unavailable, `archied` still serves chat and the +dashboard. Autonomous tasks park with an explicit capability error; they never +fall back to a host model loop. + +The bundled update adapter snapshots the configured `[containers].image` before +rebuilding it and restores that image if the restarted daemon fails its health +check. A custom image reference is therefore supported directly in +`config.toml`; `ARCHIE_AGENT_IMAGE` is only an override for deployments that +cannot make that configuration file available to the update command. + +## 5. Optional: External Compose NATS + +External NATS changes only broker deployment. It does not change the worker +executor. Start the optional service and configure the pinned Compose gateway: + +```bash +docker compose up -d nats +``` + +```toml +[nats] +mode = "external" +url = "nats://172.19.0.1:4222" + +[containers] +network = "archie-core_default" +``` + +The daemon hands workers the URL its own client connected to. The Compose +service name is not resolvable from the native host, and localhost inside a +worker is the worker itself; the pinned network gateway is reachable from both. + +`pull_policy = "always"` cannot authenticate to a private registry because the +daemon sends no registry credentials to the Docker API. Refresh a private image +with the operator's Docker credentials and retain `pull_policy = "missing"`: ```bash docker compose pull agent ``` -**Paths.** Under compose the daemon saw bind-mounted paths; on the host it sees -the real ones. In particular `db_path` is the state-path prefix from which the -daemon derives independent task and conversation SQLite files; it must point -at the intended host location, or the daemon starts against empty files. +`db_path` and other paths are native host paths. Point them at the intended +state directory; changing from an old containerized daemon path can otherwise +start Archie against empty state files. diff --git a/docker-compose.yml b/docker-compose.yml index 400552f3d..3e3fe0a5c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,11 +1,13 @@ -# archie-core stack: NATS, plus the agent image the daemon spawns per task. +# Optional external NATS, plus the agent image the daemon spawns per task. # # archied itself runs on the host under systemd, not here -- its chat tools # operate on host files, which a container cannot reach. See # deployments/systemd-user-service.md. # -# Start: docker compose up -d -# Stop: docker compose down +# Embedded NATS is the normal deployment and needs no Compose service. +# External broker: docker compose up -d nats +# Build worker: docker compose build agent +# Stop external: docker compose down # Logs: journalctl --user -u archied -f (the daemon) # docker compose logs -f nats (the bus) @@ -52,11 +54,9 @@ services: volumes: nats_data: -# The subnet is pinned because the daemon hands agent containers its own -# NATS URL verbatim (daemon.go). Running on the host, that URL has to be one -# both sides can reach: the gateway address works from the host and from any -# container on this network. Letting Docker pick the subnet would silently -# move that address when the network is recreated. +# The subnet is pinned for the optional external-broker profile because its +# configured URL must be reachable from both the native daemon and workers. +# Embedded mode discovers its selected bridge gateway at startup instead. networks: default: ipam: diff --git a/docs/architecture/configuration.md b/docs/architecture/configuration.md index a85f9237f..90f07a8ef 100644 --- a/docs/architecture/configuration.md +++ b/docs/architecture/configuration.md @@ -149,21 +149,21 @@ existing structure combines different owners. | `DiffCapLines` | root `Config` | Agent-change policy value. | | `MaxSteps`, `WallClock`, `GateMaxFailures` | `Budgets` | Workflow-execution policy, with units and zero/unlimited semantics made explicit. | | `Class`, `APIKeyEnv`, `BaseURL` | `Provider` | Provider instance settings. Secret lookup becomes a `SecretRef`, not an environment variable name leaking into the provider domain. | -| `Mode`, `Command`, `Env` | `Agent` | Agent-execution infrastructure settings. Arbitrary environment injection is explicitly trust-sensitive. | +| `Mode`, `Command`, `Env` | `LegacyAgent` | Decode-only compatibility input for the removed executor selector. Delete after the config migration window; it has no runtime settings owner. | | `Type`, `Host`, `Token` / `TokenEnv` (older form) | `Forge` | Forge adapter settings. The older `TokenEnv` input is accepted only at the loader boundary. | | `Trigger`, `AckReaction`, label names | `Dispatch` | Work-intake and forge presentation policy. Label vocabulary is configurable per forge/identity association. | | `Provider`, `ProviderConfig`, `SessionTTL` | `MemoryConfig` | Memory capability settings. Provider-specific data remains owned and validated by that provider. | | `Name`, `Transport`, `Command`, `Args`, `WorkDir`, `URL` | `MCPServer` | One typed MCP server instance specification. Transport-specific variants must reject fields belonging to other variants. | | `MaxResultChars`, `ParallelExecution` | `ToolPolicy` | Tool-execution policy values, not generic daemon configuration. | | `URL`, `TokenEnv` | `NATSConfig` | NATS transport settings with a secret reference replacing the environment-name field. | -| `Enabled`, `Image`, `MaxConcurrency`, `MaxUptime`, `VolumeTTL`, `PullPolicy`, `Network` | `ContainerConfig` | Container-execution infrastructure settings and resource policy. | +| `Image`, `MaxConcurrency`, `MaxUptime`, `VolumeTTL`, `PullPolicy`, `Network` | `ContainerConfig` | Mandatory managed-worker infrastructure settings and resource policy. The legacy `enabled` input is decode-only. | | model mappings, email, webhook, Telegram | `ChatConfig` | Separate channel instance settings plus channel-routing associations; there is no chat-wide settings owner. | | `AllowedUserIDs`, `TokenEnv`, update commands | Telegram config | Telegram adapter settings and access policy. Secret and policy fields are distinct. | | listen/relay addresses | email config | Email adapter instance settings. | | webhook target | `Notify` | Notification adapter instance settings. | | web listen address | `Web` | Web transport settings. | | index directory and database path | `Indexing` | Index infrastructure settings, derived from storage settings unless explicitly overridden. | -| forge, dispatch, models, providers, agent, containers, memory, tools, indexing and repositories | `IdentityConfig` | Existing composite duplicates unrelated settings. Replace it with associations from an `IdentityID` to independently owned configured instances. | +| forge, dispatch, models, providers, containers, memory, tools, indexing and repositories | `IdentityConfig` | Existing composite duplicates unrelated settings. Replace it with associations from an `IdentityID` to independently owned configured instances. | | owner, name, base, gate, protection, ecosystem, preflight, storage, retry and concurrency | `Repo` | Split across work intake, workspace, workflow execution, policy, gate, and scheduling as described in Repository settings. | | `TaskConfig`, `TaskForge` | worker snapshot | Replace with the minimum immutable, versioned WorkflowExecution input assembled by the application. It is not a second configuration model. | | `Extra` and arbitrary maps | root/provider config | Allowed only at an extension boundary whose owning plugin/provider supplies schema and validation. Core configuration never consumes an untyped catch-all. | diff --git a/docs/prds/embedded-nats.md b/docs/prds/embedded-nats.md index a54766909..bdf2dabcc 100644 --- a/docs/prds/embedded-nats.md +++ b/docs/prds/embedded-nats.md @@ -1,6 +1,6 @@ # Embedded NATS execution -- decision -**Status:** Amended; implementation in progress +**Status:** Implemented **Date:** 2026-08-24 @@ -31,9 +31,9 @@ NATS has two supported deployment shapes: Both shapes have identical task semantics: one container and one full-task request per workflow. Broker placement must not select a different executor. -The legacy `nats.mode = "off"`, `agent.mode = "inprocess"`, per-stage NATS, and -subprocess execution paths are migration inputs only and will be removed rather -than retained as production fallbacks. +The legacy `agent` section and `containers.enabled` key remain decode-only +migration inputs. `nats.mode = "off"`, per-stage NATS, in-process execution, +and subprocess execution are not production choices. SQLite remains authoritative for task state. NATS is the sole autonomous work handoff. SQLite recovery may identify work that needs republishing, but it must diff --git a/docs/prds/event-capture-storage.md b/docs/prds/event-capture-storage.md index fc5fb8eb5..3833fc904 100644 --- a/docs/prds/event-capture-storage.md +++ b/docs/prds/event-capture-storage.md @@ -1,6 +1,6 @@ # Event capture storage -- decision -**Status:** Decided, not yet implemented +**Status:** Implemented **Date:** 2026-08-22 **Beads issue:** `archie-core-t2db.1` @@ -20,15 +20,14 @@ stream is introduced for capture. ### Why -**NATS is not unconditionally available today.** `config.NATSConfig.URL` -empty means no NATS client is constructed (`bootstrap.go`); embedded NATS -(`7d5u.2`) that would remove this gap is still open. `t2db.1`'s own -acceptance criteria require single-process behaviour to be a *deliberate* -decision, not an accident -- making capture NATS-only today would silently -regress the `local-ollama-standalone.toml` deployment profile, which this -epic's own precondition line ("capture is the precondition for everything -else") argues against. SQLite is the one store guaranteed present in every -deployment shape, because it already backs task state unconditionally. +**NATS availability does not make capture a broker concern.** NATS is now +unconditional for autonomous workflow handoff, including embedded mode, but +capture is also used by deployments with no repository workflow configured. +SQLite is already guaranteed present because it backs daemon state, and keeps +capture inspection independent of broker retention and consumer lifecycle. +The original version of this decision cited optional NATS as an additional +reason; that premise was superseded by `archie-core-q15y`, while the storage +fit and independence arguments remain. **Capture's access pattern doesn't need what JetStream is for.** JetStream earns its complexity for reaction delivery (`7d5u.2`) because multiple diff --git a/install.sh b/install.sh index 381f24717..ee9878991 100755 --- a/install.sh +++ b/install.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # ============================================================================== -# install.sh - Installer for Archie Core (archied & archie-agent) +# install.sh - Installer for Archie Core (native archied + managed agent image) # # Follows the XDG Base Directory Specification: # Config: ${XDG_CONFIG_HOME:-~/.config}/archie @@ -17,7 +17,6 @@ # - plugins/ # Bin: ${XDG_BIN_HOME:-~/.local/bin} # - archied -# - archie-agent # ============================================================================== set -euo pipefail @@ -127,7 +126,7 @@ echo " [OK] go: ${GO_VERSION}" if command -v docker &>/dev/null; then echo " [OK] docker: $(docker --version)" else - echo " [INFO] docker is not installed (required only for NATS container mode)." + echo " [WARN] Docker is required for autonomous workflows; chat and the dashboard can still run without it." fi # 2. Create directory structure according to XDG standards @@ -160,8 +159,10 @@ else fi fi -# 4. Build and install binaries -echo "==> Building archied and archie-agent..." +# 4. Build and install the native daemon. archie-agent is deployed only as +# the managed task image; installing a host binary would imply an unsupported +# host execution path. +echo "==> Building native archied..." ( cd "${SRC_DIR}" # installtype.buildType must be stamped here: an unstamped archied @@ -171,10 +172,9 @@ echo "==> Building archied and archie-agent..." GATEWAY_VERSION="$(git describe --tags --match 'archied/v*' 2>/dev/null | sed 's|^archied/v||' || echo dev)" RUNTIME_VERSION="$(git describe --tags --match 'archie/v*' 2>/dev/null | sed 's|^archie/v||' || echo dev)" go build -ldflags "-X main.gatewayVersion=${GATEWAY_VERSION} -X main.runtimeVersion=${RUNTIME_VERSION} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" -o "${ARCHIE_BIN_DIR}/archied" ./cmd/archied - go build -o "${ARCHIE_BIN_DIR}/archie-agent" ./cmd/archie-agent install -m755 "${SRC_DIR}/scripts/archie-update-install" "${ARCHIE_BIN_DIR}/archie-update-install" ) -echo " Installed binaries and updater to ${ARCHIE_BIN_DIR}/" +echo " Installed archied and updater to ${ARCHIE_BIN_DIR}/" # 5. Interactive Configuration: Forge & LLM Provider Setup if [ ! -f "${ENV_FILE}" ]; then @@ -377,9 +377,12 @@ builder = "ollama/${OLLAMA_MODEL}" [providers.ollama] class = "ollama" -[agent] -mode = "inprocess" -command = "archie-agent" +[nats] +mode = "embedded" + +[containers] +image = "ghcr.io/samcharles93/archie-agent:latest" +pull_policy = "missing" [budgets] max_steps = 60 @@ -493,7 +496,7 @@ echo "============================================================" echo "" echo "Installation Details:" echo " - Binaries : ${ARCHIE_BIN_DIR}/archied" -echo " ${ARCHIE_BIN_DIR}/archie-agent" +echo " - Agent image: ghcr.io/samcharles93/archie-agent:latest" echo " - Config : ${ARCHIE_CONFIG_DIR}/config.toml" echo " - Secrets : ${ENV_FILE}" echo " - Data : ${ARCHIE_DATA_DIR}/" diff --git a/internal/config/config.go b/internal/config/config.go index 8aa77aa27..d22dba39f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -615,7 +615,6 @@ func cloneStringSlices(ss [][]string) [][]string { const ( NATSModeEmbedded = "embedded" NATSModeExternal = "external" - NATSModeOff = "off" ) // NATSConfig configures NATS JetStream for task distribution and reaction @@ -623,14 +622,12 @@ const ( // // "embedded" – an in-process nats-server (default; no external server) // "external" – connect to URL (required) -// "off" – no NATS; the SQLite ClaimNext flow is used unchanged // // An empty Mode resolves from URL: URL set means "external", URL empty means -// "embedded". This is a meaning change from the previous behaviour, where an -// empty URL alone meant "no NATS, SQLite only" -- that old behaviour is now -// the explicit opt-out Mode == "off" (docs/prds/embedded-nats.md). +// "embedded". Autonomous workflow handoff always uses NATS; there is no +// broker-off execution mode (docs/prds/embedded-nats.md). type NATSConfig struct { - // Mode selects embedded, external or off. Empty resolves from URL. + // Mode selects embedded or external. Empty resolves from URL. Mode string `toml:"mode" yaml:"mode"` // URL is the NATS server address, e.g. "nats://localhost:4222". // Required when Mode is "external"; must be empty otherwise. @@ -668,8 +665,10 @@ type CaptureConfig struct { // ContainerConfig configures Docker sandbox execution of archie-agent. type ContainerConfig struct { - // Enabled activates autonomous workflow execution in managed containers. - Enabled bool `toml:"enabled" yaml:"enabled"` + // LegacyEnabled decodes the removed containers.enabled switch so existing + // operator files keep loading. It has no runtime consumer: autonomous + // workflows always require managed task containers. + LegacyEnabled bool `toml:"enabled" yaml:"enabled"` // Image is the Docker image to run (e.g. "ghcr.io/sam/archie-agent:latest"). Image string `toml:"image" yaml:"image"` // MaxConcurrency limits simultaneous daemon tasks and containers. diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 1318a641c..dae4f0ca3 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -66,7 +66,8 @@ type Daemon struct { // ConnectedNATS is the endpoint and credential the daemon's own client // connected with at startup. Container env is built from this, not from // live config or environment, so reload cannot point new containers at a - // broker the daemon is not publishing on. Zero value means no NATS. + // broker the daemon is not publishing on. The zero value is invalid in + // production composition and remains useful only to fail closed in tests. ConnectedNATS NATSEndpoint Store store.TaskStore Forge forge.Forge @@ -639,7 +640,7 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, cfg config.Config // becomes a task. func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error { if d.Tasks == nil { - return fmt.Errorf("publish task %s: no task bus configured (nats.mode is off)", task.Ref()) + return fmt.Errorf("publish task %s: no task bus configured", task.Ref()) } if err := task.Kind.Validate(); err != nil { return fmt.Errorf("publish task %s: %w", task.Ref(), err) diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index e7eb88fe7..0d14f5639 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -24,6 +24,7 @@ const ( defaultContainerUptime = 60 * time.Minute defaultVolumeTTL = 72 * time.Hour defaultPullPolicy = "missing" + defaultContainerImage = "ghcr.io/samcharles93/archie-agent:latest" // defaultMaxResultChars bounds one tool result. It matches the 50KB the // lifted workspace tools already truncate themselves at @@ -191,9 +192,7 @@ func applyForgeDefaults(cfg *config.Config) { } // applyNATSDefaults resolves the nats mode from URL when the operator left it -// unset. URL set implies external; URL empty implies embedded. The previous -// behaviour -- URL empty meaning "no NATS, SQLite only" -- is now the explicit -// opt-out nats.mode = "off" (docs/prds/embedded-nats.md). +// unset. URL set implies external; URL empty implies embedded. func applyNATSDefaults(cfg *config.Config) { if cfg.NATS.Mode == "" { if cfg.NATS.URL != "" { @@ -240,11 +239,11 @@ func applyIdentityDefaults(cfg *config.Config) { } } -// applyContainerDefaults fills the container lifetimes. A negative VolumeTTL -// is left alone for validation to reject rather than silently corrected. +// applyContainerDefaults makes managed task workers usable without an explicit +// [containers] section. A negative VolumeTTL is left for validation to reject. func applyContainerDefaults(cfg *config.Config) { - if !cfg.Containers.Enabled { - return + if cfg.Containers.Image == "" { + cfg.Containers.Image = defaultContainerImage } if cfg.Containers.MaxUptime == 0 { cfg.Containers.MaxUptime = config.Duration(defaultContainerUptime) diff --git a/internal/infrastructure/configuration/defaults_test.go b/internal/infrastructure/configuration/defaults_test.go index c45252498..de3cfcec3 100644 --- a/internal/infrastructure/configuration/defaults_test.go +++ b/internal/infrastructure/configuration/defaults_test.go @@ -16,7 +16,6 @@ func TestApplyNATSDefaultsResolvesMode(t *testing.T) { }{ {name: "url set implies external", url: "nats://localhost:4222", want: config.NATSModeExternal}, {name: "empty implies embedded", want: config.NATSModeEmbedded}, - {name: "explicit off is preserved", mode: config.NATSModeOff, want: config.NATSModeOff}, {name: "explicit embedded is preserved", mode: config.NATSModeEmbedded, want: config.NATSModeEmbedded}, {name: "explicit external is preserved", mode: config.NATSModeExternal, url: "nats://localhost:4222", want: config.NATSModeExternal}, } @@ -31,6 +30,25 @@ func TestApplyNATSDefaultsResolvesMode(t *testing.T) { } } +func TestApplyContainerDefaultsMakesManagedWorkersReadyByDefault(t *testing.T) { + cfg := &config.Config{} + applyContainerDefaults(cfg) + + const wantImage = "ghcr.io/samcharles93/archie-agent:latest" + if cfg.Containers.Image != wantImage { + t.Errorf("Containers.Image = %q, want %q", cfg.Containers.Image, wantImage) + } + if cfg.Containers.MaxUptime.Std() != defaultContainerUptime { + t.Errorf("Containers.MaxUptime = %s, want %s", cfg.Containers.MaxUptime.Std(), defaultContainerUptime) + } + if cfg.Containers.VolumeTTL.Std() != defaultVolumeTTL { + t.Errorf("Containers.VolumeTTL = %s, want %s", cfg.Containers.VolumeTTL.Std(), defaultVolumeTTL) + } + if cfg.Containers.PullPolicy != defaultPullPolicy { + t.Errorf("Containers.PullPolicy = %q, want %q", cfg.Containers.PullPolicy, defaultPullPolicy) + } +} + func TestApplyForgeDefaultsIntake(t *testing.T) { cfg := &config.Config{} applyForgeDefaults(cfg) diff --git a/internal/infrastructure/configuration/dir_test.go b/internal/infrastructure/configuration/dir_test.go index 7e3aab9f4..3cd76f6c6 100644 --- a/internal/infrastructure/configuration/dir_test.go +++ b/internal/infrastructure/configuration/dir_test.go @@ -546,7 +546,6 @@ func tmpConfigDir(t *testing.T) string { // url: nats://nats.example:4222 // token_env: NATS_TOKEN // containers: -// enabled: true // image: ghcr.io/sam/archie-agent:latest // max_concurrency: 4 // pull_policy: always @@ -559,9 +558,6 @@ func tmpConfigDir(t *testing.T) string { // if cfg.NATS.URL != "nats://nats.example:4222" { // t.Errorf("NATS.URL = %q", cfg.NATS.URL) // } -// if !cfg.Containers.Enabled { -// t.Error("Containers should be enabled") -// } // if cfg.Containers.Image != "ghcr.io/sam/archie-agent:latest" { // t.Errorf("Containers.Image = %q", cfg.Containers.Image) // } diff --git a/internal/infrastructure/configuration/loader_test.go b/internal/infrastructure/configuration/loader_test.go index c8fce5325..f96eb5c9e 100644 --- a/internal/infrastructure/configuration/loader_test.go +++ b/internal/infrastructure/configuration/loader_test.go @@ -2,6 +2,7 @@ package configuration import ( "encoding/json" + "fmt" "os" "path/filepath" "strings" @@ -41,6 +42,29 @@ func TestLoadDispatchAckReaction(t *testing.T) { } } +func TestLegacyContainersEnabledCannotSelectExecutionTopology(t *testing.T) { + for _, enabled := range []bool{false, true} { + t.Run(map[bool]string{false: "disabled", true: "enabled"}[enabled], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + contents := fmt.Sprintf("bot_user = \"widget\"\n[forge]\ntype = \"none\"\n[containers]\nenabled = %t\n", enabled) + if err := os.WriteFile(path, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + + doc, err := New(nil).File(path) + if err != nil { + t.Fatal(err) + } + if doc.Config.Containers.LegacyEnabled != enabled { + t.Errorf("LegacyEnabled = %v, want decoded %v", doc.Config.Containers.LegacyEnabled, enabled) + } + if doc.Config.Containers.Image != defaultContainerImage { + t.Errorf("Image = %q, want mandatory default %q", doc.Config.Containers.Image, defaultContainerImage) + } + }) + } +} + func TestLoadExpandsConfiguredHomePaths(t *testing.T) { home, err := os.UserHomeDir() if err != nil { diff --git a/internal/infrastructure/configuration/overlay/overlay_test.go b/internal/infrastructure/configuration/overlay/overlay_test.go index 1affe494b..d0f7ba7b6 100644 --- a/internal/infrastructure/configuration/overlay/overlay_test.go +++ b/internal/infrastructure/configuration/overlay/overlay_test.go @@ -25,7 +25,7 @@ func TestSetGetSnapshotRoundTrip(t *testing.T) { }{ {"budgets.max_steps", "12"}, {"label", `"archie"`}, - {"containers.enabled", "true"}, + {"containers.image", `"archie-agent:test"`}, {"web.listen", `":8643"`}, } { if err := s.Set(ctx, tc.key, tc.value, "test"); err != nil { @@ -52,8 +52,8 @@ func TestSetGetSnapshotRoundTrip(t *testing.T) { if !ok { t.Fatalf("containers = %#v, want map", snap["containers"]) } - if got := containers["enabled"]; got != true { - t.Errorf("containers.enabled = %#v, want true", got) + if got := containers["image"]; got != "archie-agent:test" { + t.Errorf("containers.image = %#v, want archie-agent:test", got) } web, ok := snap["web"].(map[string]any) if !ok { diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index f9e87f156..7a3c73fe3 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -28,7 +28,7 @@ const ( var ( forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea, forgeTypeNone, forgeTypeOff, forgeTypeDisabled} dispatchTriggers = []string{dispatchTriggerAssignee, dispatchTriggerLabel, dispatchTriggerEither} - natsModes = []string{config.NATSModeEmbedded, config.NATSModeExternal, config.NATSModeOff} + natsModes = []string{config.NATSModeEmbedded, config.NATSModeExternal} forgeIntakes = []string{config.ForgeIntakePoll, config.ForgeIntakeWebhook, config.ForgeIntakeBoth} ) @@ -155,11 +155,6 @@ func validateForgeIntake(cfg *config.Config) error { if cfg.Forge.WebhookAddr == "" { return fmt.Errorf("%w: forge.webhook_addr is required when forge.intake is %q", ErrInvalidInput, intake) } - // Webhook intake publishes to the task queue, which is NATS (embedded - // or external). nats.mode="off" leaves no queue to publish to. - if effectiveNATSMode(cfg) == config.NATSModeOff { - return fmt.Errorf("%w: forge.intake %q requires NATS (nats.mode must not be %q)", ErrInvalidInput, intake, config.NATSModeOff) - } } return nil } @@ -269,7 +264,7 @@ func validateNATS(cfg *config.Config) error { if cfg.NATS.URL == "" { return fmt.Errorf("%w: nats.url is required when nats.mode is %q", ErrInvalidInput, config.NATSModeExternal) } - case config.NATSModeEmbedded, config.NATSModeOff: + case config.NATSModeEmbedded: if cfg.NATS.URL != "" { return fmt.Errorf("%w: nats.url must be empty when nats.mode is %q", ErrInvalidInput, mode) } @@ -277,18 +272,11 @@ func validateNATS(cfg *config.Config) error { return nil } -// validateContainers checks the combination container execution requires. -// Embedded and external NATS are both worker-reachable deployment shapes; -// composition resolves the Docker bridge gateway for embedded mode. +// validateContainers checks the mandatory managed-worker configuration. +// Embedded and external NATS are both worker-reachable deployment shapes. func validateContainers(cfg *config.Config) error { - if !cfg.Containers.Enabled { - return nil - } if cfg.Containers.Image == "" { - return fmt.Errorf("%w: containers.image is required when containers.enabled is true", ErrInvalidInput) - } - if effectiveNATSMode(cfg) == config.NATSModeOff { - return fmt.Errorf("%w: nats.mode must not be %q when containers.enabled is true", ErrInvalidInput, config.NATSModeOff) + return fmt.Errorf("%w: containers.image is required for autonomous workflow workers", ErrInvalidInput) } if cfg.Containers.VolumeTTL < 0 { return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput) diff --git a/internal/infrastructure/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index 7d00622ae..41dcc0873 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -22,6 +22,9 @@ func minimalValidConfig() config.Config { Trigger: "assignee", }, Forge: config.Forge{Type: "none"}, + Containers: config.ContainerConfig{ + Image: "ghcr.io/samcharles93/archie-agent:latest", + }, } } @@ -198,11 +201,11 @@ func TestValidateNATS(t *testing.T) { {name: "unset mode with url resolves external", url: "nats://localhost:4222"}, {name: "unset mode without url resolves embedded"}, {name: "embedded with no url", mode: config.NATSModeEmbedded}, - {name: "off with no url", mode: config.NATSModeOff}, + {name: "removed off mode", mode: "off", wantErr: true}, {name: "external with url", mode: config.NATSModeExternal, url: "nats://localhost:4222"}, {name: "external without url", mode: config.NATSModeExternal, wantErr: true}, {name: "embedded with url", mode: config.NATSModeEmbedded, url: "nats://localhost:4222", wantErr: true}, - {name: "off with url", mode: config.NATSModeOff, url: "nats://localhost:4222", wantErr: true}, + {name: "removed off mode with url", mode: "off", url: "nats://localhost:4222", wantErr: true}, {name: "unknown mode", mode: "not-a-mode", wantErr: true}, } for _, tc := range tests { @@ -225,10 +228,10 @@ func TestValidateNATS(t *testing.T) { // containers enabled and a url but no explicit mode must validate the same way // the loader's on-disk form does (url implies external), rather than diverge // because validateContainers saw an empty mode. -func TestValidateContainersResolvesNATSMode(t *testing.T) { +func TestValidateContainersSupportsBothBrokerDeployments(t *testing.T) { base := func() config.Config { cfg := minimalValidConfig() - cfg.Containers = config.ContainerConfig{Enabled: true, Image: "archie-agent:latest"} + cfg.Containers = config.ContainerConfig{Image: "archie-agent:latest"} return cfg } @@ -267,7 +270,6 @@ func TestValidateForgeIntake(t *testing.T) { {name: "webhook requires addr", intake: config.ForgeIntakeWebhook, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, wantErr: true}, {name: "webhook with secret and addr is valid", intake: config.ForgeIntakeWebhook, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, addr: "0.0.0.0:8645"}, {name: "both with secret and addr is valid", intake: config.ForgeIntakeBoth, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, addr: "0.0.0.0:8645"}, - {name: "webhook with nats off is rejected", intake: config.ForgeIntakeWebhook, secret: secret.SecretRef{Engine: "env", Key: "SECRET"}, addr: "0.0.0.0:8645", natsMode: config.NATSModeOff, wantErr: true}, {name: "unknown intake", intake: "not-a-mode", wantErr: true}, } for _, tc := range tests { diff --git a/internal/infrastructure/eventbus/nats/doc.go b/internal/infrastructure/eventbus/nats/doc.go index bbd858958..3f65cce01 100644 --- a/internal/infrastructure/eventbus/nats/doc.go +++ b/internal/infrastructure/eventbus/nats/doc.go @@ -21,6 +21,6 @@ // publisher.go publishing // consumer.go fetching // -// When no NATS URL is configured the daemon uses its local SQLite claim flow -// instead; nothing here is required for single-process operation. +// An absent URL selects the authenticated embedded broker; external URLs change +// broker placement only. There is no single-process autonomous fallback. package nats diff --git a/internal/releaseupdate/install_script_test.go b/internal/releaseupdate/install_script_test.go index 321b725d1..f9683336d 100644 --- a/internal/releaseupdate/install_script_test.go +++ b/internal/releaseupdate/install_script_test.go @@ -41,9 +41,10 @@ func TestUpdateInstallRuntimeOnlySkipsGatewayBuild(t *testing.T) { "ARCHIE_UPDATE_AGENT_VERSION": "1.10.0", }) - assertCallContains(t, calls, "go build", "./cmd/archie-agent") assertCallAbsent(t, calls, "./cmd/archied") - assertCallContains(t, calls, "docker compose build", "--build-arg RUNTIME_VERSION=1.10.0", "agent") + assertCallAbsent(t, calls, "./cmd/archie-agent") + assertCallContains(t, calls, "docker image save", "registry.example/archie-agent:stable") + assertCallContains(t, calls, "docker build", "--build-arg RUNTIME_VERSION=1.10.0", "--tag registry.example/archie-agent:stable") if got := result.Installed[ComponentAgent]; got != "1.10.0" { t.Fatalf("installed agent = %q, want 1.10.0", got) } @@ -52,7 +53,7 @@ func TestUpdateInstallRuntimeOnlySkipsGatewayBuild(t *testing.T) { } } -func TestUpdateInstallBothComponentsBuildsAndInstallsBoth(t *testing.T) { +func TestUpdateInstallBothComponentsBuildsDaemonAndManagedWorkerImage(t *testing.T) { result, calls := runUpdateInstallScript(t, map[string]string{ "ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0", "ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0", @@ -61,8 +62,9 @@ func TestUpdateInstallBothComponentsBuildsAndInstallsBoth(t *testing.T) { }) assertCallContains(t, calls, "go build", "./cmd/archied") - assertCallContains(t, calls, "go build", "./cmd/archie-agent") - assertCallContains(t, calls, "docker compose build", "RUNTIME_VERSION=1.10.0") + assertCallAbsent(t, calls, "./cmd/archie-agent") + assertCallContains(t, calls, "docker image save", "registry.example/archie-agent:stable") + assertCallContains(t, calls, "docker build", "RUNTIME_VERSION=1.10.0", "--tag registry.example/archie-agent:stable") if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.10.0" { t.Fatalf("installed = %#v, want both release versions", result.Installed) } @@ -82,22 +84,27 @@ func TestUpdateInstallNoopDoesNotFetchBuildInstallOrRestart(t *testing.T) { } } -func TestUpdateWatchdogRollsBackAndReportsOnlyChangedComponents(t *testing.T) { +func TestUpdateWatchdogRollsBackManagedWorkerImageAndReportsOnlyChangedComponents(t *testing.T) { tests := []struct { - name string - components string - wantDaemon string - wantAgent string + name string + components string + wantDaemon string + wantImageRollback bool }{ - {name: "gateway only", components: "daemon", wantDaemon: "old daemon", wantAgent: "new agent"}, - {name: "runtime only", components: "agent", wantDaemon: "new daemon", wantAgent: "old agent"}, - {name: "both", components: "daemon,agent", wantDaemon: "old daemon", wantAgent: "old agent"}, + {name: "gateway only", components: "daemon", wantDaemon: "old daemon"}, + {name: "runtime only", components: "agent", wantDaemon: "new daemon", wantImageRollback: true}, + {name: "both", components: "daemon,agent", wantDaemon: "old daemon", wantImageRollback: true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - report, daemon, agent := runUpdateWatchdogFailure(t, tt.components) - if daemon != tt.wantDaemon || agent != tt.wantAgent { - t.Fatalf("binaries after rollback = daemon %q agent %q, want %q / %q", daemon, agent, tt.wantDaemon, tt.wantAgent) + report, daemon, calls := runUpdateWatchdogFailure(t, tt.components) + if daemon != tt.wantDaemon { + t.Fatalf("daemon after rollback = %q, want %q", daemon, tt.wantDaemon) + } + if tt.wantImageRollback { + assertCallContains(t, calls, "docker image load", "archie-agent-image.prev.tar") + } else { + assertCallAbsent(t, calls, "docker image load") } if !report.RolledBack || report.HealthCheck != "failed" { t.Fatalf("report = %#v, want failed rollback", report) @@ -120,11 +127,15 @@ func runUpdateInstallScript(t *testing.T, environment map[string]string) (Result } work := t.TempDir() binDir := filepath.Join(work, "bin") + configPath := filepath.Join(work, "config.toml") fakeDir := filepath.Join(work, "fake-bin") callsPath := filepath.Join(work, "calls") if err := os.MkdirAll(binDir, 0o755); err != nil { t.Fatal(err) } + if err := os.WriteFile(configPath, []byte("[containers]\nimage = 'registry.example/archie-agent:stable'\n"), 0o600); err != nil { + t.Fatal(err) + } for _, name := range []string{"archied", "archie-agent"} { if err := os.WriteFile(filepath.Join(binDir, name), []byte("old "+name), 0o755); err != nil { t.Fatal(err) @@ -159,7 +170,18 @@ done mkdir -p "$(dirname "$out")" printf 'built\n' > "$out" `) - writeFakeCommand(t, fakeDir, "docker", `printf '%s\n' "docker $*" >> "$ARCHIE_TEST_CALLS"`) + writeFakeCommand(t, fakeDir, "docker", ` +printf '%s\n' "docker $*" >> "$ARCHIE_TEST_CALLS" +if [ "$1" = image ] && [ "$2" = save ]; then + while [ "$#" -gt 0 ]; do + if [ "$1" = --output ]; then + : > "$2" + break + fi + shift + done +fi +`) writeFakeCommand(t, fakeDir, "systemd-run", `printf '%s\n' "systemd-run $*" >> "$ARCHIE_TEST_CALLS"`) writeFakeCommand(t, fakeDir, "install", ` printf '%s\n' "install $*" >> "$ARCHIE_TEST_CALLS" @@ -188,6 +210,7 @@ printf '%s\n' "cp $*" >> "$ARCHIE_TEST_CALLS" "PATH="+fakeDir+":"+os.Getenv("PATH"), "ARCHIE_REPO_DIR="+root, "ARCHIE_BIN_DIR="+binDir, + "ARCHIE_CONFIG_PATH="+configPath, "ARCHIE_TEST_CALLS="+callsPath, ) for key, value := range environment { @@ -233,7 +256,7 @@ func writeFakeCommand(t *testing.T, dir, name, body string) { } } -func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, string) { +func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, []string) { t.Helper() root, err := filepath.Abs(filepath.Join("..", "..")) if err != nil { @@ -248,7 +271,7 @@ func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, } files := map[string]string{ "archied": "new daemon", "archied.prev": "old daemon", - "archie-agent": "new agent", "archie-agent.prev": "old agent", + "archie-agent-image.prev.tar": "saved old image", } for name, content := range files { if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil { @@ -257,12 +280,16 @@ func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, } writeFakeCommand(t, fakeDir, "systemctl", `exit 0`) writeFakeCommand(t, fakeDir, "curl", `exit 1`) + writeFakeCommand(t, fakeDir, "docker", `printf '%s\n' "docker $*" >> "$ARCHIE_TEST_CALLS"`) + callsPath := filepath.Join(work, "calls") cmd := exec.Command(filepath.Join(root, "scripts", "archie-update-watchdog")) cmd.Env = append( os.Environ(), "PATH="+fakeDir+":"+os.Getenv("PATH"), "ARCHIE_BIN_DIR="+binDir, + "ARCHIE_TEST_CALLS="+callsPath, + "ARCHIE_AGENT_IMAGE=registry.example/archie-agent:stable", "ARCHIE_UPDATE_REPORT_PATH="+reportPath, "ARCHIE_UPDATE_HEALTH_TIMEOUT=0", "ARCHIE_UPDATE_COMPONENTS="+components, @@ -286,11 +313,15 @@ func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string, if err != nil { t.Fatal(err) } - agent, err := os.ReadFile(filepath.Join(binDir, "archie-agent")) - if err != nil { + callsData, err := os.ReadFile(callsPath) + if err != nil && !os.IsNotExist(err) { t.Fatal(err) } - return report, string(daemon), string(agent) + var calls []string + if len(callsData) > 0 { + calls = strings.Split(strings.TrimSpace(string(callsData)), "\n") + } + return report, string(daemon), calls } func assertCallContains(t *testing.T, calls []string, fragments ...string) { diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 6f9909ac3..b084d9ece 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -282,7 +282,6 @@ type StorageView struct { // ContainersView is how sandboxed task execution is configured. type ContainersView struct { - Enabled bool `json:"enabled"` Image string `json:"image,omitempty"` MaxConcurrency int `json:"max_concurrency"` MaxUptime string `json:"max_uptime"` @@ -347,7 +346,6 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { SecretEngineDir: cfg.SecretEngineDir, }, Containers: ContainersView{ - Enabled: cfg.Containers.Enabled, Image: cfg.Containers.Image, MaxConcurrency: cfg.Containers.MaxConcurrency, MaxUptime: cfg.Containers.MaxUptime.Std().String(), diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index d96fcbf1c..aa0e48ce1 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -146,6 +146,15 @@ func TestHandleConfigSafeFieldsPresent(t *testing.T) { if strings.Contains(w.Body.String(), `"agent"`) { t.Errorf("removed agent execution selector leaked through config API: %s", w.Body) } + var raw struct { + Containers map[string]any `json:"containers"` + } + if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil { + t.Fatalf("decode raw config view: %v", err) + } + if _, exists := raw.Containers["enabled"]; exists { + t.Errorf("removed container execution switch leaked through config API: %s", w.Body) + } } // TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced diff --git a/scripts/archie-update-install b/scripts/archie-update-install index a46d73be4..4bec8e858 100755 --- a/scripts/archie-update-install +++ b/scripts/archie-update-install @@ -13,8 +13,40 @@ json_escape() { REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}" BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}" +CONFIG_PATH="${ARCHIE_CONFIG_PATH:-${XDG_CONFIG_HOME:-$HOME/.config}/archie/config.toml}" export PATH="/usr/local/go/bin:$PATH" +# The worker image is daemon configuration, not an updater-specific setting. +# Honour an explicit environment override for nonstandard deployers; otherwise +# read the [containers] image from the same config archied starts with. This +# deliberately understands only that one scalar, rather than trying to parse +# general TOML in shell. The daemon remains the authority for validation. +configured_agent_image() { + local image + image="$(awk ' + /^\[containers\][[:space:]]*(#.*)?$/ { in_containers = 1; next } + /^\[/ { in_containers = 0 } + in_containers && /^[[:space:]]*image[[:space:]]*=/ { + value = $0 + sub(/^[[:space:]]*image[[:space:]]*=[[:space:]]*/, "", value) + sub(/[[:space:]]*(#.*)?$/, "", value) + if (value ~ /^".*"$/) { + sub(/^"/, "", value) + sub(/"$/, "", value) + print value + } else if (length(value) >= 2 && substr(value, 1, 1) == sprintf("%c", 39) && substr(value, length(value), 1) == sprintf("%c", 39)) { + print substr(value, 2, length(value) - 2) + } + exit + } + ' "$CONFIG_PATH" 2>/dev/null || true)" + printf '%s' "$image" +} + +AGENT_IMAGE="${ARCHIE_AGENT_IMAGE:-$(configured_agent_image)}" +AGENT_IMAGE="${AGENT_IMAGE:-ghcr.io/samcharles93/archie-agent:latest}" +AGENT_IMAGE_BACKUP="$BIN_DIR/archie-agent-image.prev.tar" + PREV_GW="${ARCHIE_UPDATE_DAEMON_PREVIOUS:-}" PREV_RT="${ARCHIE_UPDATE_AGENT_PREVIOUS:-}" GW_TARGET="${ARCHIE_UPDATE_DAEMON_VERSION:-}" @@ -97,12 +129,6 @@ if [[ ",$components," == *,daemon,* ]]; then go build -ldflags "-X main.gatewayVersion=$GW -X main.runtimeVersion=$RT -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" \ -o "$tmp/archied" ./cmd/archied fi -if [[ ",$components," == *,agent,* ]]; then - echo "==> building archie-agent $RT" - go build -ldflags "-X github.com/samcharles93/archie-core/internal/app/agentworker.version=$RT -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary" \ - -o "$tmp/archie-agent" ./cmd/archie-agent -fi - if [[ ",$components," == *,daemon,* ]]; then echo "==> backing up current archied binary" [ -f "$BIN_DIR/archied" ] && cp -f "$BIN_DIR/archied" "$BIN_DIR/archied.prev" @@ -110,12 +136,10 @@ if [[ ",$components," == *,daemon,* ]]; then install -m755 "$tmp/archied" "$BIN_DIR/archied" fi if [[ ",$components," == *,agent,* ]]; then - echo "==> backing up current archie-agent binary" - [ -f "$BIN_DIR/archie-agent" ] && cp -f "$BIN_DIR/archie-agent" "$BIN_DIR/archie-agent.prev" - echo "==> installing archie-agent" - install -m755 "$tmp/archie-agent" "$BIN_DIR/archie-agent" - echo "==> rebuilding agent image for runtime $RT" - docker compose build --build-arg "RUNTIME_VERSION=$RT" agent + echo "==> saving managed worker image $AGENT_IMAGE for rollback" + docker image save --output "$AGENT_IMAGE_BACKUP" "$AGENT_IMAGE" + echo "==> rebuilding managed worker image $AGENT_IMAGE for runtime $RT" + docker build --build-arg "RUNTIME_VERSION=$RT" --tag "$AGENT_IMAGE" . fi echo "==> handing off to the update watchdog for restart and health verification" @@ -131,6 +155,8 @@ systemd-run --user --unit=archied-update-restart --collect --quiet \ --setenv=ARCHIE_UPDATE_PREVIOUS_RUNTIME="$PREV_RT" \ --setenv=ARCHIE_UPDATE_INSTALLED_GATEWAY="$GW" \ --setenv=ARCHIE_UPDATE_INSTALLED_RUNTIME="$RT" \ + --setenv=ARCHIE_AGENT_IMAGE="$AGENT_IMAGE" \ + --setenv=ARCHIE_AGENT_IMAGE_BACKUP="$AGENT_IMAGE_BACKUP" \ "$BIN_DIR/archie-update-watchdog" case "$components" in diff --git a/scripts/archie-update-watchdog b/scripts/archie-update-watchdog index 4dfebc0df..da61ec855 100755 --- a/scripts/archie-update-watchdog +++ b/scripts/archie-update-watchdog @@ -8,6 +8,8 @@ set -uo pipefail BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}" +AGENT_IMAGE="${ARCHIE_AGENT_IMAGE:-ghcr.io/samcharles93/archie-agent:latest}" +AGENT_IMAGE_BACKUP="${ARCHIE_AGENT_IMAGE_BACKUP:-$BIN_DIR/archie-agent-image.prev.tar}" HEALTH_URL="${ARCHIE_HEALTH_URL:-http://127.0.0.1:8420}" REPORT_PATH="${ARCHIE_UPDATE_REPORT_PATH:-}" HEALTH_TIMEOUT_SECONDS="${ARCHIE_UPDATE_HEALTH_TIMEOUT:-60}" @@ -72,6 +74,14 @@ rollback_component() { cp -f "$BIN_DIR/$name.prev" "$BIN_DIR/$name" } +rollback_agent_image() { + if [ ! -f "$AGENT_IMAGE_BACKUP" ]; then + echo "==> no backup for managed worker image $AGENT_IMAGE; cannot roll it back automatically" >&2 + return 1 + fi + docker image load --input "$AGENT_IMAGE_BACKUP" +} + echo "==> restarting archied.service" systemctl --user restart archied.service @@ -92,17 +102,17 @@ case "$COMPONENTS" in fi ;; agent) - if [ -f "$BIN_DIR/archie-agent.prev" ]; then - rollback_component archie-agent && rolled_back=true + if [ -f "$AGENT_IMAGE_BACKUP" ]; then + rollback_agent_image && rolled_back=true else - echo "==> no backup for archie-agent; cannot roll it back automatically" >&2 + echo "==> no backup for managed worker image $AGENT_IMAGE; cannot roll it back automatically" >&2 fi ;; daemon,agent) # Preserve the old all-or-nothing rollback guarantee: never restore one # component and leave the other on the failed release. - if [ -f "$BIN_DIR/archied.prev" ] && [ -f "$BIN_DIR/archie-agent.prev" ]; then - if rollback_component archied && rollback_component archie-agent; then + if [ -f "$BIN_DIR/archied.prev" ] && [ -f "$AGENT_IMAGE_BACKUP" ]; then + if rollback_agent_image && rollback_component archied; then rolled_back=true fi else diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index ee42b9868..06a2caa75 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -7,7 +7,7 @@ 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 I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(e){return e==null||e===``?`—`:String(e)}function K(t,n,r){let i=ie(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`—`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>se(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>ae(f,u,r)),f}function ae(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,m.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,oe(e,String(n.message||n))})}function oe(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function se(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let h=()=>n(t,...a);f.addEventListener(`click`,h),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&h()}),d.addEventListener(`click`,async()=>{let e=ce(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await m.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}var le={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ue={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function de(t){return t.length?fe(`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Component`,`Install type`,`Running`,`Latest available`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,{title:[`Installed claim: ${t.installed_claim||`unknown`}`,`Running: ${t.running_version||`not observed`}`,t.reference?`Reference: ${t.reference}`:null].filter(Boolean).join(` -`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.storage,t.containers,a),Ce(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,Se(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function Se(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Ce(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var we=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function Te(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ee(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...we.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Me(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(je(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(De(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(De(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Oe)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function De(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Oe(t){let n=t.fields||{};return e(`div.log-row.log-${Te(t.level)}`,e(`span.log-time.mono`,Ae(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(ke(n))))))}function ke(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ae(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function je(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Me(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Ne(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Pe(t)]:[o]}function Pe(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Fe(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Fe(t.headers)))))}function Fe(t){return t?e(`pre.capture-payload`,Ie(t)):e(`div.capture-empty`,`(empty)`)}function Ie(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Le(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Ne(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Re=[`string`,`number`,`bool`,`object`,`array`,`any`];function ze(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function Be(e,t){return e?`${e}.${t}`:t}function Ve(e,t){return`${e}[${t}]`}function He(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ve(n,t)]):Object.entries(t).map(([e,t])=>[e,t,Be(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:ze(n),name:t})}},t),He(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:ze(t),name:r})}},JSON.stringify(t))}function Ue(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Re.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,We(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function We(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function Ge(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Ke(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>Ge(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ue(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):He(o.payload,{onPick:p})))}return t}function qe(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Je)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Je(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ye(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ye(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Xe=`
+`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.storage,t.containers,a),Ce(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,Se(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function Se(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Ce(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var we=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function Te(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ee(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...we.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Me(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(je(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(De(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(De(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Oe)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function De(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Oe(t){let n=t.fields||{};return e(`div.log-row.log-${Te(t.level)}`,e(`span.log-time.mono`,Ae(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(ke(n))))))}function ke(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ae(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function je(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Me(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Ne(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Pe(t)]:[o]}function Pe(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Fe(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Fe(t.headers)))))}function Fe(t){return t?e(`pre.capture-payload`,Ie(t)):e(`div.capture-empty`,`(empty)`)}function Ie(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Le(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Ne(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Re=[`string`,`number`,`bool`,`object`,`array`,`any`];function ze(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function Be(e,t){return e?`${e}.${t}`:t}function Ve(e,t){return`${e}[${t}]`}function He(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ve(n,t)]):Object.entries(t).map(([e,t])=>[e,t,Be(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:ze(n),name:t})}},t),He(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:ze(t),name:r})}},JSON.stringify(t))}function Ue(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Re.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,We(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function We(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function Ge(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Ke(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>Ge(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ue(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):He(o.payload,{onPick:p})))}return t}function qe(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Je)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Je(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ye(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ye(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Xe=`
ARCHIE WORKSPACE

Chat

diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 2aa35774c..e626832c0 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -266,7 +266,6 @@ function storageCard(storage, containers, ctx) { el("h3.cfg-subhead", "Sandboxed containers"), el( "div.kv-list", - 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 }),