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.
This commit is contained in:
sam committed 2026-08-24 14:56:57 +10:00
1 parent d3da153768
commit 1f05dbb33c
38 files changed
+497 -232

No files matched your search

+17 -14
View File
@@ -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 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 the default, and not an architectural requirement. Where the daemon runs and
whether the jail is lifted together determine which filesystem those tools can 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 reach; neither is something the code should assume. `archied` and embedded NATS
archie-agent containers are Docker regardless. 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 **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 `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 `d.ConnectedNATS.URL`, captured at construction. That endpoint must therefore
runs *and* from inside the containers. When the daemon is on the host, that be reachable from wherever the daemon runs *and* from inside the containers.
means the compose network's gateway address, not the service name and not Embedded mode resolves the selected Docker bridge first and binds its
localhost. `docker-compose.yml` pins the subnet to `172.19.0.0/16` so the authenticated listener to that bridge's host gateway. External mode needs an
gateway address cannot drift when the network is recreated. 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 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 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 daemon sends no credentials to the Docker API. Refresh the agent image
explicitly instead: `docker compose pull agent`. explicitly instead: `docker compose pull agent`.
**`docker-compose.yml`** carries only NATS and the agent build stanza. The agent **`docker-compose.yml`** is optional in the default embedded deployment. It
has a `build` profile so `up -d` skips it — without the profile, compose creates carries an external NATS service plus the agent build stanza. The agent has a
a container that exits 0 immediately and reports "Started", which reads as a `build` profile so `up -d nats` never starts it as a service — without the
crash loop. `docker compose build agent` and `docker compose pull agent` still profile, Compose creates a container that exits 0 immediately and reports
work by name without activating the profile. "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 **Config lives outside the repo**, at
`${XDG_CONFIG_HOME:-~/.config}/archie/config.toml`. Nothing in the repo working `${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`. Run a single test: `go test ./internal/domain/workflow/... -run TestName -v`.
Docker/NATS stack: `task docker-build` (builds the agent image locally), Docker helpers: `task docker-build` builds the agent image locally;
`task docker-up`, `task docker-down`, `task docker-logs`. `task docker-up`, `task docker-down`, and `task docker-logs` manage the optional
external NATS service.
## Repository hygiene ## Repository hygiene
+2 -1
View File
@@ -3,7 +3,8 @@
# Language packages are installed at runtime via uv/npm/go. # Language packages are installed at runtime via uv/npm/go.
# #
# Build: docker build -t archie-agent:latest . # 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 ─────────────────────────────────────────────────────────── # ── builder ───────────────────────────────────────────────────────────
FROM golang:1.26-trixie AS builder FROM golang:1.26-trixie AS builder
+2 -2
View File
@@ -157,9 +157,9 @@ tasks:
- docker compose build agent - docker compose build agent
docker-up: docker-up:
desc: Start the NATS service via docker compose desc: Start the optional external NATS service via docker compose
cmds: cmds:
- docker compose up -d - docker compose up -d nats
docker-down: docker-down:
desc: Stop the docker compose stack desc: Stop the docker compose stack
+7 -14
View File
@@ -354,13 +354,9 @@ func (b *boot) setupObservability() {
// connectNATS opens the NATS client. External mode dials cfg.NATS.URL; // connectNATS opens the NATS client. External mode dials cfg.NATS.URL;
// embedded mode starts an in-process nats-server and dials it, so single- // embedded mode starts an in-process nats-server and dials it, so single-
// process deployments get task distribution and reaction delivery without a // 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 { func (b *boot) connectNATS(ctx context.Context) error {
cfg, log := b.cfg, b.log cfg, log := b.cfg, b.log
if cfg.NATS.Mode == config.NATSModeOff {
return nil
}
url := cfg.NATS.URL url := cfg.NATS.URL
var natsToken string var natsToken string
if cfg.NATS.Mode == config.NATSModeExternal { if cfg.NATS.Mode == config.NATSModeExternal {
@@ -412,13 +408,10 @@ func (b *boot) connectNATS(ctx context.Context) error {
return nil return nil
} }
// setupContainers builds the optional container pool. Container setup // setupContainers builds the managed autonomous-worker pool. Failure degrades
// degrades rather than aborting, for the same reason resolveForge does: // rather than aborting because the native interactive agent and dashboard do
// containers are one capability among many, and refusing to start denies // not require Docker; repository tasks park instead of falling back to a host
// the operator chat, the dashboard and every other subsystem over a // model loop.
// 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.
func (b *boot) setupContainers(ctx context.Context) func() { func (b *boot) setupContainers(ctx context.Context) func() {
containerPool, storeBackend, closeDocker := startContainers(ctx, b.cfg, b.log) containerPool, storeBackend, closeDocker := startContainers(ctx, b.cfg, b.log)
b.containerPool = containerPool b.containerPool = containerPool
@@ -1251,8 +1244,8 @@ func (b *boot) startServices(ctx context.Context) error {
return nil return nil
} }
// setupBackends wires the optional runtime backends: the NATS client // setupBackends wires the autonomous-workflow backends. Container setup may
// and the container pool. // degrade, but NATS startup must succeed because there is no other task handoff.
func (b *boot) setupBackends(ctx context.Context) error { func (b *boot) setupBackends(ctx context.Context) error {
closeContainers := b.setupContainers(ctx) closeContainers := b.setupContainers(ctx)
err := b.connectNATS(ctx) err := b.connectNATS(ctx)
@@ -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)
}
}
}
}
+13 -13
View File
@@ -723,6 +723,12 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u
if err != nil { if err != nil {
return nil, err 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() { return func() {
if err := sub.Unsubscribe(); err != nil { if err := sub.Unsubscribe(); err != nil {
log.Warn("task event unsubscribe failed", "err", err) 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 return fb, fallback
} }
// startContainers brings up the container pool and storage backend, returning // startContainers brings up the mandatory autonomous-worker pool and storage
// nils when containers are disabled or unavailable. // backend, returning a degraded nil pool when Docker is unavailable.
// //
// Failure here degrades rather than aborting, for the same reason resolveForge // Failure here degrades rather than aborting: the native interactive agent and
// does: containers are one capability among many, and refusing to start denies // dashboard remain useful without Docker, while autonomous tasks park because
// the operator chat, the dashboard and every other subsystem over a feature // there is deliberately no host execution fallback.
// 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.
func startContainers( func startContainers(
ctx context.Context, ctx context.Context,
cfg config.Config, cfg config.Config,
log *slog.Logger, log *slog.Logger,
) (*container.Pool, storage.Backend, func()) { ) (*container.Pool, storage.Backend, func()) {
noop := func() {} noop := func() {}
if !cfg.Containers.Enabled {
return nil, nil, noop
}
// Single Docker client shared between pool and storage backend. // Single Docker client shared between pool and storage backend.
dockerCli, err := client.New(client.FromEnv) dockerCli, err := client.New(client.FromEnv)
if err != nil { 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 return nil, nil, noop
} }
closeDocker := func() { closeDocker := func() {
@@ -991,7 +991,7 @@ func startContainers(
// A missing image is recoverable by hand. The daemon sends no registry // A missing image is recoverable by hand. The daemon sends no registry
// credentials on pull (internal/container/pool.go), so a private // credentials on pull (internal/container/pool.go), so a private
// registry always needs the operator's CLI to fetch it first. // 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") "hint", "run `docker compose pull agent` (or `build agent`) so the image is present locally")
return nil, storage.NewDockerBackend(dockerCli), closeDocker return nil, storage.NewDockerBackend(dockerCli), closeDocker
} }
+10
View File
@@ -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")
}
}
+2 -2
View File
@@ -165,7 +165,7 @@ var reloadableFields = map[string]bool{
// reloadableSubFields are sub-fields of structs that are otherwise // reloadableSubFields are sub-fields of structs that are otherwise
// startup-built. VolumeTTL is re-read per cycle in cleanupExpiredStorage; // 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 // MaxUptime, PullPolicy, Network) is frozen in the startup-built
// container pool -- the dispatchers re-read MaxConcurrency but the pool // container pool -- the dispatchers re-read MaxConcurrency but the pool
// captures it at construction (container/pool.go:94,163), so a change // 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 // forge client itself is startup-built, so Type/Token/TokenEnv stay
// requires-restart. // requires-restart.
var reloadableSubFields = map[string]map[string]bool{ var reloadableSubFields = map[string]map[string]bool{
"Containers": {"VolumeTTL": true}, "Containers": {"LegacyEnabled": true, "VolumeTTL": true},
"Forge": {"Host": true}, "Forge": {"Host": true},
} }
+5
View File
@@ -219,6 +219,11 @@ func TestChangedNonReloadableFields(t *testing.T) {
if got := changedNonReloadableFields(base, legacyOnly); len(got) != 0 { if got := changedNonReloadableFields(base, legacyOnly); len(got) != 0 {
t.Fatalf("legacy agent change: got %v, want []", got) 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 // Containers sub-field granularity: Image change warns, MaxConcurrency
// and VolumeTTL changes do not. // and VolumeTTL changes do not.
+11 -22
View File
@@ -165,17 +165,6 @@ class = "ollama"
# args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"] # args = ["-y", "@wonderwhy-er/desktop-commander@0.2.46", "--no-onboarding"]
# work_dir = "/path/to/workspace" # 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. # Workspace code-search index. Paths default under work_dir when unset.
[indexing] [indexing]
# Code-search index files (default: <work_dir>/indexes). # Code-search index files (default: <work_dir>/indexes).
@@ -228,15 +217,13 @@ max_steps = 60
wall_clock = "30m" wall_clock = "30m"
gate_max_failures = 5 gate_max_failures = 5
# NATS JetStream for task distribution and reaction delivery. mode selects # NATS is the sole autonomous workflow handoff. mode changes only where the
# how NATS is provided: # broker runs; every workflow still runs in a managed task container:
# "embedded" – in-process nats-server (the default; no external server) # "embedded" – in-process nats-server (the default; no external server)
# "external" – connect to url # "external" – connect to url
# "off" – no NATS; the SQLite ClaimNext flow is used for tasks # Leave the section absent to run embedded.
# Leave the section absent (or set no url) to run embedded; set mode="off"
# only to opt out of NATS entirely.
# [nats] # [nats]
# mode = "embedded" # "embedded" | "external" | "off" # mode = "embedded" # "embedded" | "external"
# url = "nats://localhost:4222" # required when mode = "external" # url = "nats://localhost:4222" # required when mode = "external"
# token_env = "NATS_TOKEN" # optional external-server credential; embedded generates one per start # 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_per_second = 1.0 # per-remote-address token bucket
# rate_burst = 5 # rate_burst = 5
# Docker sandbox execution of archie-agent. This is the only autonomous # Docker sandbox execution of archie-agent is mandatory for autonomous
# workflow execution path; embedded and external NATS are both supported. # 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] # [containers]
# enabled = true # image = "ghcr.io/samcharles93/archie-agent:latest"
# image = "archie-agent:latest" # Docker image to run # max_concurrency = 4 # optional cap; 0/absent means no global cap
# max_concurrency = 4 # max simultaneous tasks/containers
# max_uptime = "60m" # container lifetime cap # max_uptime = "60m" # container lifetime cap
# volume_ttl = "72h" # max age for persistent repo volumes and Git clone caches # volume_ttl = "72h" # max age for persistent repo volumes and Git clone caches
# pull_policy = "missing" # "missing" or "always" # pull_policy = "missing" # "missing" or "always"
+105
View File
@@ -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")
}
}
+2 -6
View File
@@ -38,19 +38,15 @@ parked = "agent:parked"
# Stages run in sandboxed archie-agent containers over NATS. archied only # Stages run in sandboxed archie-agent containers over NATS. archied only
# orchestrates: the agent image carries the toolchain and makes the model # orchestrates: the agent image carries the toolchain and makes the model
# calls, so gate commands resolve there, not in the daemon image. Setting # calls, so gate commands resolve there, not in the native daemon.
# containers.enabled selects nats mode on its own, but pinning it here keeps
# the intent explicit.
[agent]
mode = "nats"
[nats] [nats]
mode = "external"
# The pinned Compose-network gateway is reachable from both the host daemon # The pinned Compose-network gateway is reachable from both the host daemon
# and the task containers it launches on archie-core_default. # and the task containers it launches on archie-core_default.
url = "nats://172.19.0.1:4222" url = "nats://172.19.0.1:4222"
[containers] [containers]
enabled = true
network = "archie-core_default" network = "archie-core_default"
image = "git.example.com/you/archie-agent:latest" image = "git.example.com/you/archie-agent:latest"
max_concurrency = 4 max_concurrency = 4
-4
View File
@@ -31,10 +31,6 @@ models = [
"ollama/qwen2.5:7b" "ollama/qwen2.5:7b"
] ]
[agent]
mode = "inprocess"
command = "archie-agent"
[budgets] [budgets]
max_steps = 60 max_steps = 60
wall_clock = "30m" wall_clock = "30m"
+6 -3
View File
@@ -19,9 +19,12 @@ builder = "openai/gpt-4o"
class = "openai" class = "openai"
api_key_env = "OPENAI_API_KEY" api_key_env = "OPENAI_API_KEY"
[agent] [nats]
mode = "inprocess" mode = "embedded"
command = "archie-agent"
[containers]
image = "ghcr.io/samcharles93/archie-agent:latest"
pull_policy = "missing"
[budgets] [budgets]
max_steps = 60 max_steps = 60
+6 -3
View File
@@ -38,9 +38,12 @@ builder = "openai/gpt-4o"
class = "openai" class = "openai"
api_key_env = "OPENAI_API_KEY" api_key_env = "OPENAI_API_KEY"
[agent] [nats]
mode = "inprocess" mode = "embedded"
command = "archie-agent"
[containers]
image = "ghcr.io/samcharles93/archie-agent:latest"
pull_policy = "missing"
[budgets] [budgets]
max_steps = 60 max_steps = 60
+55 -20
View File
@@ -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 Embedded NATS is the default. The systemd service runs `archied` natively, so
`docker compose up -d` keeps running the bus and holds the network the agents interactive chat keeps the host access the operator configured, while every
join. Two things bite in this hybrid layout: 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 Docker must be installed and reachable by the service user. With no explicit
containers its own `nats.url` verbatim, so `nats://nats:4222` (resolvable only broker or container settings, Archie uses embedded NATS and the published
inside compose) and `nats://127.0.0.1:4222` (the container's own loopback) are `ghcr.io/samcharles93/archie-agent:latest` image. An explicit equivalent is:
both wrong. Use the compose network's gateway address, which the host and the
containers can both reach:
```toml ```toml
[nats] [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 At startup Archie resolves the Docker bridge used by its task containers,
network is recreated. 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 If Docker or the image is unavailable, `archied` still serves chat and the
calls the Docker API with no registry credentials, so `"always"` gets a 401, dashboard. Autonomous tasks park with an explicit capability error; they never
which fails the container pool and exits the daemon. Refresh the agent image fall back to a host model loop.
by hand instead:
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 ```bash
docker compose pull agent docker compose pull agent
``` ```
**Paths.** Under compose the daemon saw bind-mounted paths; on the host it sees `db_path` and other paths are native host paths. Point them at the intended
the real ones. In particular `db_path` is the state-path prefix from which the state directory; changing from an old containerized daemon path can otherwise
daemon derives independent task and conversation SQLite files; it must point start Archie against empty state files.
at the intended host location, or the daemon starts against empty files.
+8 -8
View File
@@ -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 # archied itself runs on the host under systemd, not here -- its chat tools
# operate on host files, which a container cannot reach. See # operate on host files, which a container cannot reach. See
# deployments/systemd-user-service.md. # deployments/systemd-user-service.md.
# #
# Start: docker compose up -d # Embedded NATS is the normal deployment and needs no Compose service.
# Stop: docker compose down # 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) # Logs: journalctl --user -u archied -f (the daemon)
# docker compose logs -f nats (the bus) # docker compose logs -f nats (the bus)
@@ -52,11 +54,9 @@ services:
volumes: volumes:
nats_data: nats_data:
# The subnet is pinned because the daemon hands agent containers its own # The subnet is pinned for the optional external-broker profile because its
# NATS URL verbatim (daemon.go). Running on the host, that URL has to be one # configured URL must be reachable from both the native daemon and workers.
# both sides can reach: the gateway address works from the host and from any # Embedded mode discovers its selected bridge gateway at startup instead.
# container on this network. Letting Docker pick the subnet would silently
# move that address when the network is recreated.
networks: networks:
default: default:
ipam: ipam:
+3 -3
View File
@@ -149,21 +149,21 @@ existing structure combines different owners.
| `DiffCapLines` | root `Config` | Agent-change policy value. | | `DiffCapLines` | root `Config` | Agent-change policy value. |
| `MaxSteps`, `WallClock`, `GateMaxFailures` | `Budgets` | Workflow-execution policy, with units and zero/unlimited semantics made explicit. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | `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. | | 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. | | `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. | | listen/relay addresses | email config | Email adapter instance settings. |
| webhook target | `Notify` | Notification adapter instance settings. | | webhook target | `Notify` | Notification adapter instance settings. |
| web listen address | `Web` | Web transport settings. | | web listen address | `Web` | Web transport settings. |
| index directory and database path | `Indexing` | Index infrastructure settings, derived from storage settings unless explicitly overridden. | | 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. | | 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. | | `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. | | `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. |
+4 -4
View File
@@ -1,6 +1,6 @@
# Embedded NATS execution -- decision # Embedded NATS execution -- decision
**Status:** Amended; implementation in progress **Status:** Implemented
**Date:** 2026-08-24 **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 Both shapes have identical task semantics: one container and one full-task
request per workflow. Broker placement must not select a different executor. request per workflow. Broker placement must not select a different executor.
The legacy `nats.mode = "off"`, `agent.mode = "inprocess"`, per-stage NATS, and The legacy `agent` section and `containers.enabled` key remain decode-only
subprocess execution paths are migration inputs only and will be removed rather migration inputs. `nats.mode = "off"`, per-stage NATS, in-process execution,
than retained as production fallbacks. and subprocess execution are not production choices.
SQLite remains authoritative for task state. NATS is the sole autonomous work SQLite remains authoritative for task state. NATS is the sole autonomous work
handoff. SQLite recovery may identify work that needs republishing, but it must handoff. SQLite recovery may identify work that needs republishing, but it must
+9 -10
View File
@@ -1,6 +1,6 @@
# Event capture storage -- decision # Event capture storage -- decision
**Status:** Decided, not yet implemented **Status:** Implemented
**Date:** 2026-08-22 **Date:** 2026-08-22
**Beads issue:** `archie-core-t2db.1` **Beads issue:** `archie-core-t2db.1`
@@ -20,15 +20,14 @@ stream is introduced for capture.
### Why ### Why
**NATS is not unconditionally available today.** `config.NATSConfig.URL` **NATS availability does not make capture a broker concern.** NATS is now
empty means no NATS client is constructed (`bootstrap.go`); embedded NATS unconditional for autonomous workflow handoff, including embedded mode, but
(`7d5u.2`) that would remove this gap is still open. `t2db.1`'s own capture is also used by deployments with no repository workflow configured.
acceptance criteria require single-process behaviour to be a *deliberate* SQLite is already guaranteed present because it backs daemon state, and keeps
decision, not an accident -- making capture NATS-only today would silently capture inspection independent of broker retention and consumer lifecycle.
regress the `local-ollama-standalone.toml` deployment profile, which this The original version of this decision cited optional NATS as an additional
epic's own precondition line ("capture is the precondition for everything reason; that premise was superseded by `archie-core-q15y`, while the storage
else") argues against. SQLite is the one store guaranteed present in every fit and independence arguments remain.
deployment shape, because it already backs task state unconditionally.
**Capture's access pattern doesn't need what JetStream is for.** JetStream **Capture's access pattern doesn't need what JetStream is for.** JetStream
earns its complexity for reaction delivery (`7d5u.2`) because multiple earns its complexity for reaction delivery (`7d5u.2`) because multiple
+14 -11
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash #!/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: # Follows the XDG Base Directory Specification:
# Config: ${XDG_CONFIG_HOME:-~/.config}/archie # Config: ${XDG_CONFIG_HOME:-~/.config}/archie
@@ -17,7 +17,6 @@
# - plugins/ # - plugins/
# Bin: ${XDG_BIN_HOME:-~/.local/bin} # Bin: ${XDG_BIN_HOME:-~/.local/bin}
# - archied # - archied
# - archie-agent
# ============================================================================== # ==============================================================================
set -euo pipefail set -euo pipefail
@@ -127,7 +126,7 @@ echo " [OK] go: ${GO_VERSION}"
if command -v docker &>/dev/null; then if command -v docker &>/dev/null; then
echo " [OK] docker: $(docker --version)" echo " [OK] docker: $(docker --version)"
else 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 fi
# 2. Create directory structure according to XDG standards # 2. Create directory structure according to XDG standards
@@ -160,8 +159,10 @@ else
fi fi
fi fi
# 4. Build and install binaries # 4. Build and install the native daemon. archie-agent is deployed only as
echo "==> Building archied and archie-agent..." # the managed task image; installing a host binary would imply an unsupported
# host execution path.
echo "==> Building native archied..."
( (
cd "${SRC_DIR}" cd "${SRC_DIR}"
# installtype.buildType must be stamped here: an unstamped archied # 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)" 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)" 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 -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" 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 # 5. Interactive Configuration: Forge & LLM Provider Setup
if [ ! -f "${ENV_FILE}" ]; then if [ ! -f "${ENV_FILE}" ]; then
@@ -377,9 +377,12 @@ builder = "ollama/${OLLAMA_MODEL}"
[providers.ollama] [providers.ollama]
class = "ollama" class = "ollama"
[agent] [nats]
mode = "inprocess" mode = "embedded"
command = "archie-agent"
[containers]
image = "ghcr.io/samcharles93/archie-agent:latest"
pull_policy = "missing"
[budgets] [budgets]
max_steps = 60 max_steps = 60
@@ -493,7 +496,7 @@ echo "============================================================"
echo "" echo ""
echo "Installation Details:" echo "Installation Details:"
echo " - Binaries : ${ARCHIE_BIN_DIR}/archied" 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 " - Config : ${ARCHIE_CONFIG_DIR}/config.toml"
echo " - Secrets : ${ENV_FILE}" echo " - Secrets : ${ENV_FILE}"
echo " - Data : ${ARCHIE_DATA_DIR}/" echo " - Data : ${ARCHIE_DATA_DIR}/"
+7 -8
View File
@@ -615,7 +615,6 @@ func cloneStringSlices(ss [][]string) [][]string {
const ( const (
NATSModeEmbedded = "embedded" NATSModeEmbedded = "embedded"
NATSModeExternal = "external" NATSModeExternal = "external"
NATSModeOff = "off"
) )
// NATSConfig configures NATS JetStream for task distribution and reaction // NATSConfig configures NATS JetStream for task distribution and reaction
@@ -623,14 +622,12 @@ const (
// //
// "embedded" – an in-process nats-server (default; no external server) // "embedded" – an in-process nats-server (default; no external server)
// "external" – connect to URL (required) // "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 // 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 // "embedded". Autonomous workflow handoff always uses NATS; there is no
// empty URL alone meant "no NATS, SQLite only" -- that old behaviour is now // broker-off execution mode (docs/prds/embedded-nats.md).
// the explicit opt-out Mode == "off" (docs/prds/embedded-nats.md).
type NATSConfig struct { 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"` Mode string `toml:"mode" yaml:"mode"`
// URL is the NATS server address, e.g. "nats://localhost:4222". // URL is the NATS server address, e.g. "nats://localhost:4222".
// Required when Mode is "external"; must be empty otherwise. // Required when Mode is "external"; must be empty otherwise.
@@ -668,8 +665,10 @@ type CaptureConfig struct {
// ContainerConfig configures Docker sandbox execution of archie-agent. // ContainerConfig configures Docker sandbox execution of archie-agent.
type ContainerConfig struct { type ContainerConfig struct {
// Enabled activates autonomous workflow execution in managed containers. // LegacyEnabled decodes the removed containers.enabled switch so existing
Enabled bool `toml:"enabled" yaml:"enabled"` // 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 is the Docker image to run (e.g. "ghcr.io/sam/archie-agent:latest").
Image string `toml:"image" yaml:"image"` Image string `toml:"image" yaml:"image"`
// MaxConcurrency limits simultaneous daemon tasks and containers. // MaxConcurrency limits simultaneous daemon tasks and containers.
+3 -2
View File
@@ -66,7 +66,8 @@ type Daemon struct {
// ConnectedNATS is the endpoint and credential the daemon's own client // ConnectedNATS is the endpoint and credential the daemon's own client
// connected with at startup. Container env is built from this, not from // connected with at startup. Container env is built from this, not from
// live config or environment, so reload cannot point new containers at a // 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 ConnectedNATS NATSEndpoint
Store store.TaskStore Store store.TaskStore
Forge forge.Forge Forge forge.Forge
@@ -639,7 +640,7 @@ func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, cfg config.Config
// becomes a task. // becomes a task.
func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error { func (d *Daemon) PublishTask(ctx context.Context, task workintake.TaskEnvelope) error {
if d.Tasks == nil { 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 { if err := task.Kind.Validate(); err != nil {
return fmt.Errorf("publish task %s: %w", task.Ref(), err) return fmt.Errorf("publish task %s: %w", task.Ref(), err)
@@ -24,6 +24,7 @@ const (
defaultContainerUptime = 60 * time.Minute defaultContainerUptime = 60 * time.Minute
defaultVolumeTTL = 72 * time.Hour defaultVolumeTTL = 72 * time.Hour
defaultPullPolicy = "missing" defaultPullPolicy = "missing"
defaultContainerImage = "ghcr.io/samcharles93/archie-agent:latest"
// defaultMaxResultChars bounds one tool result. It matches the 50KB the // defaultMaxResultChars bounds one tool result. It matches the 50KB the
// lifted workspace tools already truncate themselves at // 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 // applyNATSDefaults resolves the nats mode from URL when the operator left it
// unset. URL set implies external; URL empty implies embedded. The previous // unset. URL set implies external; URL empty implies embedded.
// behaviour -- URL empty meaning "no NATS, SQLite only" -- is now the explicit
// opt-out nats.mode = "off" (docs/prds/embedded-nats.md).
func applyNATSDefaults(cfg *config.Config) { func applyNATSDefaults(cfg *config.Config) {
if cfg.NATS.Mode == "" { if cfg.NATS.Mode == "" {
if cfg.NATS.URL != "" { if cfg.NATS.URL != "" {
@@ -240,11 +239,11 @@ func applyIdentityDefaults(cfg *config.Config) {
} }
} }
// applyContainerDefaults fills the container lifetimes. A negative VolumeTTL // applyContainerDefaults makes managed task workers usable without an explicit
// is left alone for validation to reject rather than silently corrected. // [containers] section. A negative VolumeTTL is left for validation to reject.
func applyContainerDefaults(cfg *config.Config) { func applyContainerDefaults(cfg *config.Config) {
if !cfg.Containers.Enabled { if cfg.Containers.Image == "" {
return cfg.Containers.Image = defaultContainerImage
} }
if cfg.Containers.MaxUptime == 0 { if cfg.Containers.MaxUptime == 0 {
cfg.Containers.MaxUptime = config.Duration(defaultContainerUptime) cfg.Containers.MaxUptime = config.Duration(defaultContainerUptime)
@@ -16,7 +16,6 @@ func TestApplyNATSDefaultsResolvesMode(t *testing.T) {
}{ }{
{name: "url set implies external", url: "nats://localhost:4222", want: config.NATSModeExternal}, {name: "url set implies external", url: "nats://localhost:4222", want: config.NATSModeExternal},
{name: "empty implies embedded", want: config.NATSModeEmbedded}, {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 embedded is preserved", mode: config.NATSModeEmbedded, want: config.NATSModeEmbedded},
{name: "explicit external is preserved", mode: config.NATSModeExternal, url: "nats://localhost:4222", want: config.NATSModeExternal}, {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) { func TestApplyForgeDefaultsIntake(t *testing.T) {
cfg := &config.Config{} cfg := &config.Config{}
applyForgeDefaults(cfg) applyForgeDefaults(cfg)
@@ -546,7 +546,6 @@ func tmpConfigDir(t *testing.T) string {
// url: nats://nats.example:4222 // url: nats://nats.example:4222
// token_env: NATS_TOKEN // token_env: NATS_TOKEN
// containers: // containers:
// enabled: true
// image: ghcr.io/sam/archie-agent:latest // image: ghcr.io/sam/archie-agent:latest
// max_concurrency: 4 // max_concurrency: 4
// pull_policy: always // pull_policy: always
@@ -559,9 +558,6 @@ func tmpConfigDir(t *testing.T) string {
// if cfg.NATS.URL != "nats://nats.example:4222" { // if cfg.NATS.URL != "nats://nats.example:4222" {
// t.Errorf("NATS.URL = %q", cfg.NATS.URL) // 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" { // if cfg.Containers.Image != "ghcr.io/sam/archie-agent:latest" {
// t.Errorf("Containers.Image = %q", cfg.Containers.Image) // t.Errorf("Containers.Image = %q", cfg.Containers.Image)
// } // }
@@ -2,6 +2,7 @@ package configuration
import ( import (
"encoding/json" "encoding/json"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings" "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) { func TestLoadExpandsConfiguredHomePaths(t *testing.T) {
home, err := os.UserHomeDir() home, err := os.UserHomeDir()
if err != nil { if err != nil {
@@ -25,7 +25,7 @@ func TestSetGetSnapshotRoundTrip(t *testing.T) {
}{ }{
{"budgets.max_steps", "12"}, {"budgets.max_steps", "12"},
{"label", `"archie"`}, {"label", `"archie"`},
{"containers.enabled", "true"}, {"containers.image", `"archie-agent:test"`},
{"web.listen", `":8643"`}, {"web.listen", `":8643"`},
} { } {
if err := s.Set(ctx, tc.key, tc.value, "test"); err != nil { if err := s.Set(ctx, tc.key, tc.value, "test"); err != nil {
@@ -52,8 +52,8 @@ func TestSetGetSnapshotRoundTrip(t *testing.T) {
if !ok { if !ok {
t.Fatalf("containers = %#v, want map", snap["containers"]) t.Fatalf("containers = %#v, want map", snap["containers"])
} }
if got := containers["enabled"]; got != true { if got := containers["image"]; got != "archie-agent:test" {
t.Errorf("containers.enabled = %#v, want true", got) t.Errorf("containers.image = %#v, want archie-agent:test", got)
} }
web, ok := snap["web"].(map[string]any) web, ok := snap["web"].(map[string]any)
if !ok { if !ok {
@@ -28,7 +28,7 @@ const (
var ( var (
forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea, forgeTypeNone, forgeTypeOff, forgeTypeDisabled} forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea, forgeTypeNone, forgeTypeOff, forgeTypeDisabled}
dispatchTriggers = []string{dispatchTriggerAssignee, dispatchTriggerLabel, dispatchTriggerEither} 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} forgeIntakes = []string{config.ForgeIntakePoll, config.ForgeIntakeWebhook, config.ForgeIntakeBoth}
) )
@@ -155,11 +155,6 @@ func validateForgeIntake(cfg *config.Config) error {
if cfg.Forge.WebhookAddr == "" { if cfg.Forge.WebhookAddr == "" {
return fmt.Errorf("%w: forge.webhook_addr is required when forge.intake is %q", ErrInvalidInput, intake) 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 return nil
} }
@@ -269,7 +264,7 @@ func validateNATS(cfg *config.Config) error {
if cfg.NATS.URL == "" { if cfg.NATS.URL == "" {
return fmt.Errorf("%w: nats.url is required when nats.mode is %q", ErrInvalidInput, config.NATSModeExternal) 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 != "" { if cfg.NATS.URL != "" {
return fmt.Errorf("%w: nats.url must be empty when nats.mode is %q", ErrInvalidInput, mode) 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 return nil
} }
// validateContainers checks the combination container execution requires. // validateContainers checks the mandatory managed-worker configuration.
// Embedded and external NATS are both worker-reachable deployment shapes; // Embedded and external NATS are both worker-reachable deployment shapes.
// composition resolves the Docker bridge gateway for embedded mode.
func validateContainers(cfg *config.Config) error { func validateContainers(cfg *config.Config) error {
if !cfg.Containers.Enabled {
return nil
}
if cfg.Containers.Image == "" { if cfg.Containers.Image == "" {
return fmt.Errorf("%w: containers.image is required when containers.enabled is true", ErrInvalidInput) return fmt.Errorf("%w: containers.image is required for autonomous workflow workers", ErrInvalidInput)
}
if effectiveNATSMode(cfg) == config.NATSModeOff {
return fmt.Errorf("%w: nats.mode must not be %q when containers.enabled is true", ErrInvalidInput, config.NATSModeOff)
} }
if cfg.Containers.VolumeTTL < 0 { if cfg.Containers.VolumeTTL < 0 {
return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput) return fmt.Errorf("%w: containers.volume_ttl must not be negative", ErrInvalidInput)
@@ -22,6 +22,9 @@ func minimalValidConfig() config.Config {
Trigger: "assignee", Trigger: "assignee",
}, },
Forge: config.Forge{Type: "none"}, 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 with url resolves external", url: "nats://localhost:4222"},
{name: "unset mode without url resolves embedded"}, {name: "unset mode without url resolves embedded"},
{name: "embedded with no url", mode: config.NATSModeEmbedded}, {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 with url", mode: config.NATSModeExternal, url: "nats://localhost:4222"},
{name: "external without url", mode: config.NATSModeExternal, wantErr: true}, {name: "external without url", mode: config.NATSModeExternal, wantErr: true},
{name: "embedded with url", mode: config.NATSModeEmbedded, url: "nats://localhost:4222", 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}, {name: "unknown mode", mode: "not-a-mode", wantErr: true},
} }
for _, tc := range tests { 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 // 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 // the loader's on-disk form does (url implies external), rather than diverge
// because validateContainers saw an empty mode. // because validateContainers saw an empty mode.
func TestValidateContainersResolvesNATSMode(t *testing.T) { func TestValidateContainersSupportsBothBrokerDeployments(t *testing.T) {
base := func() config.Config { base := func() config.Config {
cfg := minimalValidConfig() cfg := minimalValidConfig()
cfg.Containers = config.ContainerConfig{Enabled: true, Image: "archie-agent:latest"} cfg.Containers = config.ContainerConfig{Image: "archie-agent:latest"}
return cfg 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 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: "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: "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}, {name: "unknown intake", intake: "not-a-mode", wantErr: true},
} }
for _, tc := range tests { for _, tc := range tests {
+2 -2
View File
@@ -21,6 +21,6 @@
// publisher.go publishing // publisher.go publishing
// consumer.go fetching // consumer.go fetching
// //
// When no NATS URL is configured the daemon uses its local SQLite claim flow // An absent URL selects the authenticated embedded broker; external URLs change
// instead; nothing here is required for single-process operation. // broker placement only. There is no single-process autonomous fallback.
package nats package nats
+53 -22
View File
@@ -41,9 +41,10 @@ func TestUpdateInstallRuntimeOnlySkipsGatewayBuild(t *testing.T) {
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0", "ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
}) })
assertCallContains(t, calls, "go build", "./cmd/archie-agent")
assertCallAbsent(t, calls, "./cmd/archied") 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" { if got := result.Installed[ComponentAgent]; got != "1.10.0" {
t.Fatalf("installed agent = %q, want 1.10.0", got) 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{ result, calls := runUpdateInstallScript(t, map[string]string{
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0", "ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.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/archied")
assertCallContains(t, calls, "go build", "./cmd/archie-agent") assertCallAbsent(t, calls, "./cmd/archie-agent")
assertCallContains(t, calls, "docker compose build", "RUNTIME_VERSION=1.10.0") 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" { if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.10.0" {
t.Fatalf("installed = %#v, want both release versions", result.Installed) 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 { tests := []struct {
name string name string
components string components string
wantDaemon string wantDaemon string
wantAgent string wantImageRollback bool
}{ }{
{name: "gateway only", components: "daemon", wantDaemon: "old daemon", wantAgent: "new agent"}, {name: "gateway only", components: "daemon", wantDaemon: "old daemon"},
{name: "runtime only", components: "agent", wantDaemon: "new daemon", wantAgent: "old agent"}, {name: "runtime only", components: "agent", wantDaemon: "new daemon", wantImageRollback: true},
{name: "both", components: "daemon,agent", wantDaemon: "old daemon", wantAgent: "old agent"}, {name: "both", components: "daemon,agent", wantDaemon: "old daemon", wantImageRollback: true},
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
report, daemon, agent := runUpdateWatchdogFailure(t, tt.components) report, daemon, calls := runUpdateWatchdogFailure(t, tt.components)
if daemon != tt.wantDaemon || agent != tt.wantAgent { if daemon != tt.wantDaemon {
t.Fatalf("binaries after rollback = daemon %q agent %q, want %q / %q", daemon, agent, tt.wantDaemon, tt.wantAgent) 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" { if !report.RolledBack || report.HealthCheck != "failed" {
t.Fatalf("report = %#v, want failed rollback", report) 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() work := t.TempDir()
binDir := filepath.Join(work, "bin") binDir := filepath.Join(work, "bin")
configPath := filepath.Join(work, "config.toml")
fakeDir := filepath.Join(work, "fake-bin") fakeDir := filepath.Join(work, "fake-bin")
callsPath := filepath.Join(work, "calls") callsPath := filepath.Join(work, "calls")
if err := os.MkdirAll(binDir, 0o755); err != nil { if err := os.MkdirAll(binDir, 0o755); err != nil {
t.Fatal(err) 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"} { for _, name := range []string{"archied", "archie-agent"} {
if err := os.WriteFile(filepath.Join(binDir, name), []byte("old "+name), 0o755); err != nil { if err := os.WriteFile(filepath.Join(binDir, name), []byte("old "+name), 0o755); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -159,7 +170,18 @@ done
mkdir -p "$(dirname "$out")" mkdir -p "$(dirname "$out")"
printf 'built\n' > "$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, "systemd-run", `printf '%s\n' "systemd-run $*" >> "$ARCHIE_TEST_CALLS"`)
writeFakeCommand(t, fakeDir, "install", ` writeFakeCommand(t, fakeDir, "install", `
printf '%s\n' "install $*" >> "$ARCHIE_TEST_CALLS" printf '%s\n' "install $*" >> "$ARCHIE_TEST_CALLS"
@@ -188,6 +210,7 @@ printf '%s\n' "cp $*" >> "$ARCHIE_TEST_CALLS"
"PATH="+fakeDir+":"+os.Getenv("PATH"), "PATH="+fakeDir+":"+os.Getenv("PATH"),
"ARCHIE_REPO_DIR="+root, "ARCHIE_REPO_DIR="+root,
"ARCHIE_BIN_DIR="+binDir, "ARCHIE_BIN_DIR="+binDir,
"ARCHIE_CONFIG_PATH="+configPath,
"ARCHIE_TEST_CALLS="+callsPath, "ARCHIE_TEST_CALLS="+callsPath,
) )
for key, value := range environment { 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() t.Helper()
root, err := filepath.Abs(filepath.Join("..", "..")) root, err := filepath.Abs(filepath.Join("..", ".."))
if err != nil { if err != nil {
@@ -248,7 +271,7 @@ func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string,
} }
files := map[string]string{ files := map[string]string{
"archied": "new daemon", "archied.prev": "old daemon", "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 { for name, content := range files {
if err := os.WriteFile(filepath.Join(binDir, name), []byte(content), 0o755); err != nil { 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, "systemctl", `exit 0`)
writeFakeCommand(t, fakeDir, "curl", `exit 1`) 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 := exec.Command(filepath.Join(root, "scripts", "archie-update-watchdog"))
cmd.Env = append( cmd.Env = append(
os.Environ(), os.Environ(),
"PATH="+fakeDir+":"+os.Getenv("PATH"), "PATH="+fakeDir+":"+os.Getenv("PATH"),
"ARCHIE_BIN_DIR="+binDir, "ARCHIE_BIN_DIR="+binDir,
"ARCHIE_TEST_CALLS="+callsPath,
"ARCHIE_AGENT_IMAGE=registry.example/archie-agent:stable",
"ARCHIE_UPDATE_REPORT_PATH="+reportPath, "ARCHIE_UPDATE_REPORT_PATH="+reportPath,
"ARCHIE_UPDATE_HEALTH_TIMEOUT=0", "ARCHIE_UPDATE_HEALTH_TIMEOUT=0",
"ARCHIE_UPDATE_COMPONENTS="+components, "ARCHIE_UPDATE_COMPONENTS="+components,
@@ -286,11 +313,15 @@ func runUpdateWatchdogFailure(t *testing.T, components string) (Report, string,
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
agent, err := os.ReadFile(filepath.Join(binDir, "archie-agent")) callsData, err := os.ReadFile(callsPath)
if err != nil { if err != nil && !os.IsNotExist(err) {
t.Fatal(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) { func assertCallContains(t *testing.T, calls []string, fragments ...string) {
-2
View File
@@ -282,7 +282,6 @@ type StorageView struct {
// ContainersView is how sandboxed task execution is configured. // ContainersView is how sandboxed task execution is configured.
type ContainersView struct { type ContainersView struct {
Enabled bool `json:"enabled"`
Image string `json:"image,omitempty"` Image string `json:"image,omitempty"`
MaxConcurrency int `json:"max_concurrency"` MaxConcurrency int `json:"max_concurrency"`
MaxUptime string `json:"max_uptime"` MaxUptime string `json:"max_uptime"`
@@ -347,7 +346,6 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) {
SecretEngineDir: cfg.SecretEngineDir, SecretEngineDir: cfg.SecretEngineDir,
}, },
Containers: ContainersView{ Containers: ContainersView{
Enabled: cfg.Containers.Enabled,
Image: cfg.Containers.Image, Image: cfg.Containers.Image,
MaxConcurrency: cfg.Containers.MaxConcurrency, MaxConcurrency: cfg.Containers.MaxConcurrency,
MaxUptime: cfg.Containers.MaxUptime.Std().String(), MaxUptime: cfg.Containers.MaxUptime.Std().String(),
+9
View File
@@ -146,6 +146,15 @@ func TestHandleConfigSafeFieldsPresent(t *testing.T) {
if strings.Contains(w.Body.String(), `"agent"`) { if strings.Contains(w.Body.String(), `"agent"`) {
t.Errorf("removed agent execution selector leaked through config API: %s", w.Body) 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 // TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced
+38 -12
View File
@@ -13,8 +13,40 @@ json_escape() {
REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}" REPO="${ARCHIE_REPO_DIR:-$HOME/projects/archie-core}"
BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}" 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" 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_GW="${ARCHIE_UPDATE_DAEMON_PREVIOUS:-}"
PREV_RT="${ARCHIE_UPDATE_AGENT_PREVIOUS:-}" PREV_RT="${ARCHIE_UPDATE_AGENT_PREVIOUS:-}"
GW_TARGET="${ARCHIE_UPDATE_DAEMON_VERSION:-}" 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" \ 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 -o "$tmp/archied" ./cmd/archied
fi 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 if [[ ",$components," == *,daemon,* ]]; then
echo "==> backing up current archied binary" echo "==> backing up current archied binary"
[ -f "$BIN_DIR/archied" ] && cp -f "$BIN_DIR/archied" "$BIN_DIR/archied.prev" [ -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" install -m755 "$tmp/archied" "$BIN_DIR/archied"
fi fi
if [[ ",$components," == *,agent,* ]]; then if [[ ",$components," == *,agent,* ]]; then
echo "==> backing up current archie-agent binary" echo "==> saving managed worker image $AGENT_IMAGE for rollback"
[ -f "$BIN_DIR/archie-agent" ] && cp -f "$BIN_DIR/archie-agent" "$BIN_DIR/archie-agent.prev" docker image save --output "$AGENT_IMAGE_BACKUP" "$AGENT_IMAGE"
echo "==> installing archie-agent" echo "==> rebuilding managed worker image $AGENT_IMAGE for runtime $RT"
install -m755 "$tmp/archie-agent" "$BIN_DIR/archie-agent" docker build --build-arg "RUNTIME_VERSION=$RT" --tag "$AGENT_IMAGE" .
echo "==> rebuilding agent image for runtime $RT"
docker compose build --build-arg "RUNTIME_VERSION=$RT" agent
fi fi
echo "==> handing off to the update watchdog for restart and health verification" 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_PREVIOUS_RUNTIME="$PREV_RT" \
--setenv=ARCHIE_UPDATE_INSTALLED_GATEWAY="$GW" \ --setenv=ARCHIE_UPDATE_INSTALLED_GATEWAY="$GW" \
--setenv=ARCHIE_UPDATE_INSTALLED_RUNTIME="$RT" \ --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" "$BIN_DIR/archie-update-watchdog"
case "$components" in case "$components" in
+15 -5
View File
@@ -8,6 +8,8 @@
set -uo pipefail set -uo pipefail
BIN_DIR="${ARCHIE_BIN_DIR:-$HOME/.local/bin}" 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}" HEALTH_URL="${ARCHIE_HEALTH_URL:-http://127.0.0.1:8420}"
REPORT_PATH="${ARCHIE_UPDATE_REPORT_PATH:-}" REPORT_PATH="${ARCHIE_UPDATE_REPORT_PATH:-}"
HEALTH_TIMEOUT_SECONDS="${ARCHIE_UPDATE_HEALTH_TIMEOUT:-60}" HEALTH_TIMEOUT_SECONDS="${ARCHIE_UPDATE_HEALTH_TIMEOUT:-60}"
@@ -72,6 +74,14 @@ rollback_component() {
cp -f "$BIN_DIR/$name.prev" "$BIN_DIR/$name" 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" echo "==> restarting archied.service"
systemctl --user restart archied.service systemctl --user restart archied.service
@@ -92,17 +102,17 @@ case "$COMPONENTS" in
fi fi
;; ;;
agent) agent)
if [ -f "$BIN_DIR/archie-agent.prev" ]; then if [ -f "$AGENT_IMAGE_BACKUP" ]; then
rollback_component archie-agent && rolled_back=true rollback_agent_image && rolled_back=true
else 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 fi
;; ;;
daemon,agent) daemon,agent)
# Preserve the old all-or-nothing rollback guarantee: never restore one # Preserve the old all-or-nothing rollback guarantee: never restore one
# component and leave the other on the failed release. # component and leave the other on the failed release.
if [ -f "$BIN_DIR/archied.prev" ] && [ -f "$BIN_DIR/archie-agent.prev" ]; then if [ -f "$BIN_DIR/archied.prev" ] && [ -f "$AGENT_IMAGE_BACKUP" ]; then
if rollback_component archied && rollback_component archie-agent; then if rollback_agent_image && rollback_component archied; then
rolled_back=true rolled_back=true
fi fi
else else
+1 -1
View File
@@ -7,7 +7,7 @@
stroke-dasharray="${c}" stroke-dasharray="${c}"
stroke-dashoffset="${c*(1-i/100)}" stroke-dashoffset="${c*(1-i/100)}"
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function Line truncated class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function Line truncated
`)},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.<name>] 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:`budLine truncated `)},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.<name>] 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:`budLine truncated
<div class="chat-page-content"> <div class="chat-page-content">
<header class="chat-topbar"> <header class="chat-topbar">
<div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div> <div><span class="chat-kicker">ARCHIE WORKSPACE</span><h1 class="page-title">Chat</h1></div>
-1
View File
@@ -266,7 +266,6 @@ function storageCard(storage, containers, ctx) {
el("h3.cfg-subhead", "Sandboxed containers"), el("h3.cfg-subhead", "Sandboxed containers"),
el( el(
"div.kv-list", "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("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("Max concurrent tasks", containers.max_concurrency || "Unlimited", { key: "containers.max_concurrency", type: "int", raw: containers.max_concurrency, ...ctx }),
row("Container max lifetime", containers.max_uptime, { key: "containers.max_uptime", type: "string", raw: containers.max_uptime, ...ctx }), row("Container max lifetime", containers.max_uptime, { key: "containers.max_uptime", type: "string", raw: containers.max_uptime, ...ctx }),