From 5d00ec7b0c6fdba723ffbe74d48fd1a4bfabcd20 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 24 Aug 2026 14:21:22 +1000 Subject: [PATCH] refactor(agentexec): remove legacy execution paths Autonomous workflows now have exactly one production boundary: a task-scoped archie-agent receives a full-task core-NATS request and runs the worker-local stage loop. The legacy [agent] section remains decode-only for migration; it no longer selects runtime behavior. --- ARCHITECTURE.md | 18 +- CLAUDE.md | 17 +- cmd/archie-agent/main.go | 4 - cmd/archie-agent/main_test.go | 5 +- cmd/archied/bootstrap.go | 82 +---- cmd/archied/main.go | 6 +- cmd/archied/reload.go | 3 + cmd/archied/reload_test.go | 13 +- config.example.toml | 4 +- docs/architecture/agent-system.md | 9 +- docs/architecture/migration-decisions.md | 21 +- docs/architecture/observability.md | 27 +- docs/prds/adversarial-self-review.md | 11 +- internal/agentexec/architecture_test.go | 58 ++++ .../{inprocess.go => loop_runner.go} | 22 +- ...{inprocess_test.go => loop_runner_test.go} | 20 +- internal/agentexec/nats.go | 136 --------- internal/agentexec/nats_test.go | 285 ------------------ internal/agentexec/protocol.go | 60 +--- internal/agentexec/runtime.go | 4 +- internal/agentexec/skill_test.go | 99 ------ internal/agentexec/stage_message.go | 19 -- internal/agentexec/subjects.go | 21 +- internal/agentexec/subprocess.go | 170 ----------- internal/agentexec/subprocess_process_unix.go | 27 -- .../agentexec/subprocess_process_windows.go | 9 - internal/agentexec/subprocess_test.go | 249 --------------- internal/agentexec/taskevents.go | 3 +- internal/agentexec/toolset.go | 9 +- internal/agentexec/worker.go | 166 ---------- internal/app/agentworker/architecture_test.go | 15 + .../app/agentworker/single_stage_request.go | 95 ------ .../agentworker/single_stage_request_test.go | 123 -------- internal/app/agentworker/stage_loop.go | 57 ---- internal/app/agentworker/stage_loop_test.go | 198 ------------ internal/app/agentworker/task_execution.go | 10 +- .../app/agentworker/task_execution_test.go | 12 +- internal/app/agentworker/worker.go | 42 ++- internal/app/agentworker/worker_test.go | 60 ++-- internal/config/clone_test.go | 12 +- internal/config/config.go | 25 +- internal/container/pool.go | 4 +- internal/daemon/architecture_test.go | 34 +++ internal/daemon/daemon.go | 31 +- internal/daemon/daemon_test.go | 21 +- internal/eventbus/eventbus.go | 42 --- internal/infrastructure/agentboot/task.go | 21 +- .../infrastructure/agentboot/task_test.go | 19 +- internal/infrastructure/agentgit/safety.go | 7 +- .../agenttransport/nats/transport.go | 176 +++-------- .../agenttransport/nats/transport_test.go | 276 ++++------------- .../configuration/apply_test.go | 6 +- .../infrastructure/configuration/defaults.go | 17 -- .../configuration/loader_test.go | 25 +- .../infrastructure/configuration/validate.go | 33 +- .../configuration/validate_test.go | 30 +- .../infrastructure/eventbus/nats/message.go | 16 - .../infrastructure/eventbus/nats/publisher.go | 74 ----- internal/skillscript/yaegi_test.go | 4 +- internal/taskrun/taskrun.go | 3 +- internal/tools/provider/contract_test.go | 4 +- internal/webui/api_config.go | 15 - internal/webui/api_config_test.go | 10 +- ui/dist/assets/index.js | 10 +- ui/src/settings/settings.js | 28 -- 65 files changed, 454 insertions(+), 2678 deletions(-) create mode 100644 internal/agentexec/architecture_test.go rename internal/agentexec/{inprocess.go => loop_runner.go} (94%) rename internal/agentexec/{inprocess_test.go => loop_runner_test.go} (95%) delete mode 100644 internal/agentexec/nats.go delete mode 100644 internal/agentexec/nats_test.go delete mode 100644 internal/agentexec/skill_test.go delete mode 100644 internal/agentexec/stage_message.go delete mode 100644 internal/agentexec/subprocess.go delete mode 100644 internal/agentexec/subprocess_process_unix.go delete mode 100644 internal/agentexec/subprocess_process_windows.go delete mode 100644 internal/agentexec/subprocess_test.go delete mode 100644 internal/agentexec/worker.go delete mode 100644 internal/app/agentworker/single_stage_request.go delete mode 100644 internal/app/agentworker/single_stage_request_test.go delete mode 100644 internal/app/agentworker/stage_loop.go delete mode 100644 internal/app/agentworker/stage_loop_test.go diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 72629dd7a..fe690eb7f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -22,12 +22,12 @@ See `docs/architecture/organisation.md` for the target structure and | `internal/app/agentworker/` | Agent worker composition, lifecycle, routing, and workflow execution | | `internal/infrastructure/agentboot/` | Worker boot-brief filesystem decoding | | `internal/infrastructure/agentgit/` | Worker git safe-directory setup | -| `internal/infrastructure/agenttransport/nats/` | Worker NATS transport, stage/task wire boundaries, and RPC client construction | +| `internal/infrastructure/agenttransport/nats/` | Worker core-NATS full-task handoff and RPC client construction | | `internal/config/` | Config types only — loading lives in `infrastructure/configuration` | | `internal/daemon/` | Resident loop: poll, enqueue, claim, route, process, reconcile | | `internal/domain/workflow/` | Engine: stage lists, routing, shared steps, workflow definitions | | `internal/domain/workintake/`| `TaskEnvelope`, routing `Kind`, label vocabulary, task subjects | -| `internal/agentexec/` | Versioned agent-stage protocol, worker, and in-process/subprocess runners | +| `internal/agentexec/` | Worker-local stage protocol and ai-sdk loop runner | | `internal/forge/` | Forge interface: GitHub and Gitea implementations | | `internal/worktree/` | Git operations: clone, branch, commit, push, diff, cleanup | | `internal/store/` | Task store interface and SQLite implementation; RPC clients proxy it | @@ -195,8 +195,8 @@ Daemon-level TOML (`~/.config/archie/config.toml`): ecosystem - `[models]` -- planner, builder, triage (provider/model refs) - `[providers]` -- LLM provider configs -- `[agent]` -- execution mode (`inprocess` or `subprocess`), worker command, - environment allowlist +- `[nats]` -- embedded or external broker deployment +- `[containers]` -- managed `archie-agent` image, limits, storage, and network - `[budgets]` -- max steps, max tokens, wall clock, gate max failures - `[web]` -- dashboard listen address - `[notify]` -- webhook URL for notifications @@ -212,17 +212,11 @@ Config fields reference a secret as `{engine, key}` (`secret.SecretRef`), e.g. `token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }`. As of this writing `Forge.Token` and `Provider.APIKey` use `SecretRef`; resolved provider values -are exported under private, identity-scoped environment names because the SDK, -subprocess, and container boundaries consume credential names rather than +are exported under private, identity-scoped environment names because the SDK +and container boundary consume credential names rather than plaintext wire fields. The older `Provider.APIKeyEnv`, `NATSConfig.TokenEnv`, and `TelegramConfig.TokenEnv` field names remain supported. -Subprocess mode is a migration transport boundary, not a security sandbox: the -worker still runs under the daemon UID and can access daemon-readable host -resources. The "daemon never runs untrusted code" boundary requires the later -container runner with a separate user, a restricted filesystem and process -namespace, and explicit mounts. - Per-repo gates are command lists: `[[repos.gate]] = ["go", "vet", "./..."]`. The last command is the test runner (by convention -- TDD inverts it). diff --git a/CLAUDE.md b/CLAUDE.md index ce2f05833..d437447d6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -306,8 +306,9 @@ boundaries. Summary of what's evolved since that doc was last fully accurate: package table; see `docs/architecture/migration-decisions.md` for the recorded position and what was agreed next. - The daemon has grown an RPC split (`internal/forgerpc`, `internal/storerpc`, - `internal/worktreerpc`, `internal/natsrpc`) alongside the in-process model - described in ARCHITECTURE.md. The eventbus transport is + `internal/worktreerpc`, `internal/natsrpc`) used by the task-scoped + `archie-agent` worker. Autonomous workflows cross one full-task core-NATS + handoff; the daemon has no local workflow runner. The eventbus transport is `internal/infrastructure/eventbus/`. Check those plus `docker-compose.yml` for the current split between `archied` and sandboxed workers. - `internal/gate/` — quality gate execution (the "environmental constraints over @@ -362,12 +363,14 @@ boundaries. Summary of what's evolved since that doc was last fully accurate: conflict and the later one silently receives nothing. `nats.Client.Subscribe` creates a NEW consumer, so calling it on subjects the client's own durable consumer already filters will never deliver — drain the existing consumer with - `Fetch` instead, as `internal/app/agentworker` and the agentexec round-trip fake do. + `Fetch` instead. `internal/app/agentworker` deliberately uses core NATS only; + restoring a worker JetStream consumer would also restore the deleted + single-stage execution topology. (2) *Reply inboxes are not stream subjects.* Answering a request must use core - NATS publish, not the JetStream path: a `Message.ReplyAddress` is an ephemeral - `_INBOX.*` belonging to one waiting caller and part of no stream, so a durable - publish to it fails. That is why `eventbus.Publisher` declares `Respond` as a - method distinct from `Publish` rather than a convenience over it. + NATS: the request message's reply address is an ephemeral `_INBOX.*` belonging + to one waiting caller and part of no stream, so a durable publish to it fails. + Full-task and RPC responders use core `msg.Respond`; never route their replies + through `eventbus.Publisher`. (3) *Subscribe does not mean reachable.* `nc.Subscribe` only queues the SUB frame client-side, so code that registers a responder and immediately issues a request can beat its own subscription and get `ErrNoResponders` from a diff --git a/cmd/archie-agent/main.go b/cmd/archie-agent/main.go index d3b3564b7..eae9b7dcb 100644 --- a/cmd/archie-agent/main.go +++ b/cmd/archie-agent/main.go @@ -15,8 +15,6 @@ import ( "github.com/samcharles93/archie-core/internal/app/agentworker" ) -const consumerName = "archie-agent" - type workerRunner func(context.Context, agentworker.Settings, *slog.Logger) error func main() { @@ -31,7 +29,6 @@ func runCommand(args []string, getenv func(string) string, stderr io.Writer, run flags := flag.NewFlagSet("archie-agent", flag.ContinueOnError) flags.SetOutput(stderr) natsURLFlag := flags.String("nats-url", "", "NATS server URL (defaults to NATS_URL)") - consumer := flags.String("consumer", consumerName, "JetStream consumer name") if err := flags.Parse(args); err != nil { if errors.Is(err, flag.ErrHelp) { return 0 @@ -53,7 +50,6 @@ func runCommand(args []string, getenv func(string) string, stderr io.Writer, run if err := runWorker(ctx, agentworker.Settings{ NATSURL: natsURL, NATSToken: natsToken, - Consumer: *consumer, }, log); err != nil { return 1 } diff --git a/cmd/archie-agent/main_test.go b/cmd/archie-agent/main_test.go index ed60d8fbc..8282f189f 100644 --- a/cmd/archie-agent/main_test.go +++ b/cmd/archie-agent/main_test.go @@ -21,6 +21,7 @@ func TestRunCommandPreservesCLIExitSemantics(t *testing.T) { }{ {name: "help", args: []string{"-h"}}, {name: "flag parse error", args: []string{"-unknown"}, wantCode: 2}, + {name: "removed consumer flag", args: []string{"-consumer", "legacy"}, wantCode: 2}, {name: "missing NATS URL", wantCode: 1}, { name: "worker failure", @@ -88,8 +89,8 @@ func TestRunCommandMapsWorkerOutcomeToExitStatus(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { var stderr bytes.Buffer - code := runCommand([]string{"-nats-url", "nats://flag", "-consumer", "custom"}, func(string) string { return "token" }, &stderr, func(_ context.Context, settings agentworker.Settings, _ *slog.Logger) error { - if settings.NATSURL != "nats://flag" || settings.NATSToken != "token" || settings.Consumer != "custom" { + code := runCommand([]string{"-nats-url", "nats://flag"}, func(string) string { return "token" }, &stderr, func(_ context.Context, settings agentworker.Settings, _ *slog.Logger) error { + if settings.NATSURL != "nats://flag" || settings.NATSToken != "token" { t.Fatalf("settings = %#v", settings) } return test.workerErr diff --git a/cmd/archied/bootstrap.go b/cmd/archied/bootstrap.go index e39bcac20..21a947387 100644 --- a/cmd/archied/bootstrap.go +++ b/cmd/archied/bootstrap.go @@ -31,7 +31,6 @@ import ( "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild" - "github.com/samcharles93/archie-core/internal/domain/workflow/wfeval" "github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -107,8 +106,7 @@ type boot struct { containerPool *container.Pool storeBackend storage.Backend - providers map[string]agentexec.Provider - llm *runtime.Runtime + llm *runtime.Runtime toolReg *tools.Registry chatModels gateway.ModelManager @@ -120,8 +118,6 @@ type boot struct { webRouter *gateway.Router startGateways []func() - agentRunner agentexec.Runner - registry workflow.Registry capabilityHost *plugin.Host trees *worktree.Manager worktreeGrants *worktreerpc.Grants @@ -401,7 +397,7 @@ func (b *boot) connectNATS(ctx context.Context) error { natsClient, err := nats.Connect(ctx, nats.Config{ URL: url, Token: natsToken, - Subjects: []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard}, + Subjects: []string{workintake.SubjectTaskWildcard}, FilterSubject: workintake.SubjectTaskWildcard, }, log) if err != nil { @@ -439,7 +435,6 @@ func (b *boot) setupLLMAndChat(ctx context.Context) { // Created before gateways so the LLMResponder can be wired into the // Telegram router for non-command message processing. providers := executionProviders(cfg) - b.providers = providers b.llm = agentexec.NewRuntime(providers) b.toolReg = tools.NewRegistry() chatModels := newChatModelManager(cfg.Models, cfg.Chat.Models, b.catalogModels) @@ -582,39 +577,6 @@ func (b *boot) setupGateways(ctx context.Context, cfgPath, overlayPath string) b return true } -func (b *boot) buildAgentRunner() error { - cfg, log := b.cfg, b.log - if b.llm == nil { - return nil - } - switch cfg.Agent.Mode { - case "subprocess": - b.agentRunner = &agentexec.SubprocessRunner{ - Command: cfg.Agent.Command, - Environ: os.Environ(), - AdditionalEnv: cfg.Agent.Env, - Diagnostics: os.Stderr, - Providers: b.providers, - } - case "inprocess": - inproc := agentexec.NewInProcessRunner(b.llm, log, b.toolReg) - inproc.Limits = toolLimits(cfg) - b.agentRunner = inproc - case "nats": - if b.natsClient == nil { - log.Error("agent.mode is nats but nats is unavailable (nats.mode is off)") - return fmt.Errorf("agent.mode is nats but nats is unavailable (nats.mode is off)") - } - b.agentRunner = &agentexec.NATSRunner{ - Bus: b.natsClient, - Providers: b.providers, - MCPServers: cfg.Tools.MCPServers, - Log: log, - } - } - return nil -} - // loadWorkflows builds the workflow registry from the skill catalog. // Plugin-defined workflows override built-ins of the same name; // built-ins fill gaps. @@ -629,9 +591,8 @@ func (b *boot) loadWorkflows(ctx context.Context) error { log.Error("skill registry build failed", "err", err) return err } - b.registry = workflowCatalog.Registry - log.Info("workflow registry built", "workflows", len(b.registry)) - b.web.Workflows = workflow.DefinitionsWithOrigins(b.registry, workflowCatalog.Origins) + log.Info("workflow registry built", "workflows", len(workflowCatalog.Registry)) + b.web.Workflows = workflow.DefinitionsWithOrigins(workflowCatalog.Registry, workflowCatalog.Origins) if l := cfg.Web.Listen; l != "" && l != "off" { b.web.Token = webTokenFor(l, cfg.DBPath, log) go func() { @@ -707,29 +668,6 @@ func (b *boot) buildTreesAndIdentities(ctx context.Context) error { log.Error("identity construction failed", "identity", idCfg.Name, "err", err) return err } - idProviders := agentexec.ProvidersFromConfig(idCfg.Providers) - idRuntime := agentexec.NewRuntime(idProviders) - if idRuntime != nil { - switch cfg.Agent.Mode { - case "subprocess": - runner.Agent = &agentexec.SubprocessRunner{ - Command: cfg.Agent.Command, - Environ: os.Environ(), - AdditionalEnv: cfg.Agent.Env, - Diagnostics: os.Stderr, - Providers: idProviders, - } - case "inprocess": - idRunner := agentexec.NewInProcessRunner(idRuntime, log.With("identity", idCfg.Name), b.toolReg) - idRunner.Limits = toolLimits(cfg) - runner.Agent = idRunner - case "nats": - runner.Agent = &agentexec.NATSRunner{ - Bus: b.natsClient, Providers: idProviders, - MCPServers: cfg.Tools.MCPServers, Log: log.With("identity", idCfg.Name), - } - } - } b.identityRunners = append(b.identityRunners, runner) log.Info("identity configured", "identity", idCfg.Name, "bot_user", idCfg.BotUser, "repos", len(idCfg.Repos)) } @@ -1007,12 +945,9 @@ func (b *boot) buildDaemon() { Bus: b.bus, Forge: b.forgeClient, Trees: b.trees, - Agent: b.agentRunner, - Workflows: b.registry, CapabilityHost: b.capabilityHost, Storage: b.storeBackend, Log: log, - CustomStages: wfeval.Discover, Tasks: b.natsClient, WorktreeGrants: b.worktreeGrants, ContainerPool: b.containerPool, @@ -1329,15 +1264,6 @@ func (b *boot) setupBackends(ctx context.Context) error { return err } -// buildAgentAndWorkflows builds the agent runner and the workflow -// registry it executes. -func (b *boot) buildAgentAndWorkflows(ctx context.Context) error { - if err := b.buildAgentRunner(); err != nil { - return err - } - return b.loadWorkflows(ctx) -} - // shutdownCuratorRuntime returns a cleanup that stops the curator // runtime. The stop path derives its own timeout budget from Background // rather than the boot context, which is already cancelled by the time diff --git a/cmd/archied/main.go b/cmd/archied/main.go index db7c92d02..be7e40efd 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -360,7 +360,7 @@ func run() int { return 1 } - if err := b.buildAgentAndWorkflows(ctx); err != nil { + if err := b.loadWorkflows(ctx); err != nil { return 1 } if err := b.loadPlugins(); err != nil { @@ -704,8 +704,8 @@ func subscribeSystemLogs(nc *natsio.Conn, taskLogs *logging.TaskRegistry, log *s // in-process and invisible to the daemon; this is the other half of the // bridge, landing them on bus so persistAndBroadcastEvents -- the single // choke point that inserts into the SQLite events table and fans out over -// SSE -- treats them exactly like an in-process daemon-run workflow's own -// events. Mirrors subscribeSystemLogs's demux-by-taskID shape. +// SSE -- treats them exactly like every other daemon-observed event. Mirrors +// subscribeSystemLogs's demux-by-taskID shape. func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (unsubscribe func(), err error) { sub, err := nc.Subscribe(agentexec.SubjectEventsWildcard, func(msg *natsio.Msg) { taskID, ok := agentexec.TaskIDFromEventsSubject(msg.Subject) diff --git a/cmd/archied/reload.go b/cmd/archied/reload.go index 06c6b315f..409c9ef74 100644 --- a/cmd/archied/reload.go +++ b/cmd/archied/reload.go @@ -158,6 +158,9 @@ var reloadableFields = map[string]bool{ // per-task half of this list is pinned mechanically; this webui-only // entry is pinned by TestChangedNonReloadableFields. "MaxRetries": true, + // [agent] is a decode-only compatibility shim; changes have no runtime + // consumer and therefore require neither reload nor restart. + "LegacyAgent": true, } // reloadableSubFields are sub-fields of structs that are otherwise diff --git a/cmd/archied/reload_test.go b/cmd/archied/reload_test.go index e155330df..29b3e8037 100644 --- a/cmd/archied/reload_test.go +++ b/cmd/archied/reload_test.go @@ -31,7 +31,7 @@ func minimalConfigTOML(botUser string) string { } func invalidConfigTOML() string { - return "bot_user = \"widget\"\nagent = { mode = \"bogus-mode\" }\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" + return "bot_user = \"widget\"\ndispatch = { trigger = \"bogus-trigger\" }\n[[repos]]\nowner = \"acme\"\nname = \"app\"\n" } func TestReloadAppliesAndPublishes(t *testing.T) { @@ -212,11 +212,12 @@ func TestChangedNonReloadableFields(t *testing.T) { t.Fatalf("reloadable-only: got %v, want []", got) } - // A non-reloadable change is named (Agent builds the startup runner). - nonReloadable := base - nonReloadable.Agent = config.Agent{Mode: "subprocess"} - if got := changedNonReloadableFields(base, nonReloadable); len(got) != 1 || got[0] != "Agent" { - t.Fatalf("Agent change: got %v, want [Agent]", got) + // The removed [agent] section remains decode-only for old files. Changing + // it has no running consumer and must not claim a restart will apply it. + legacyOnly := base + legacyOnly.LegacyAgent = config.LegacyAgent{Mode: "subprocess"} + if got := changedNonReloadableFields(base, legacyOnly); len(got) != 0 { + t.Fatalf("legacy agent change: got %v, want []", got) } // Containers sub-field granularity: Image change warns, MaxConcurrency diff --git a/config.example.toml b/config.example.toml index 1cba9c0d9..240f6dd29 100644 --- a/config.example.toml +++ b/config.example.toml @@ -255,8 +255,8 @@ gate_max_failures = 5 # rate_per_second = 1.0 # per-remote-address token bucket # rate_burst = 5 -# Docker sandbox execution of archie-agent. Requires NATS and agent.mode = "nats"; -# embedded and external broker modes are both supported. +# Docker sandbox execution of archie-agent. This is the only autonomous +# workflow execution path; embedded and external NATS are both supported. # [containers] # enabled = true # image = "archie-agent:latest" # Docker image to run diff --git a/docs/architecture/agent-system.md b/docs/architecture/agent-system.md index 6c0890f21..a4e926171 100644 --- a/docs/architecture/agent-system.md +++ b/docs/architecture/agent-system.md @@ -185,7 +185,8 @@ running after crash -> queued Workflows select and sequence deterministic and agent-run stages. Implement, TDD, feasibility, and bootstrap are current Workflow definitions. -WorkflowExecutions may run in-process or be handed wholesale to `archie-agent`. +Every WorkflowExecution is handed wholesale over core NATS to a task-scoped +`archie-agent` container, which owns the workflow stage loop. ## Current workflow-feature placement @@ -222,7 +223,7 @@ each meaning deliberately; a global text replacement is prohibited. | Per-stage `agentexec.Request.TaskID` | `internal/agentexec` | WorkflowExecutionID correlation | An agent invocation is a bounded WorkflowStep execution. Correlate request/result with WorkflowExecutionID, StepExecutionID, attempt, and protocol version. | | NATS `TaskMessage` and `archie.task.*` | `internal/nats` | Channel request or WorkflowExecution transport | Discovery messages and execution dispatch are different contracts and subjects. Domain meaning stays outside NATS infrastructure. Identity and source-message idempotency must be explicit. | | `taskDispatcher` work item | `internal/daemon` | WorkflowExecution scheduling | Scheduling operates on execution references and declared concurrency policy. Repository serialization is policy, not identity derived from an incomplete task struct. | -| `container.TaskPayload` and `task.json` | `internal/container`; read by `internal/infrastructure/agentboot` | WorkflowExecution brief | Rename the boot artifact and schema. It identifies the mounted execution and required workspace only; it is not an alternative execution definition. Malformed input must fail safely rather than silently joining an unrelated shared queue. | +| `container.TaskPayload` and `task.json` | `internal/container`; read by `internal/infrastructure/agentboot` | WorkflowExecution brief | Rename the boot artifact and schema. It identifies the mounted execution and required workspace only; it is not an alternative execution definition. Missing or malformed input must fail startup before the worker subscribes. | | `storage.TaskRef` | `internal/storage` | WorkflowExecution workspace lease | Storage receives the minimal execution/workspace reference and policy required to provision and release resources. It does not receive the WorkflowExecution aggregate. | | Gateway `TaskCreator` | `internal/gateway` | Accepted work request handoff | A channel may carry a request for durable workflow-backed work, but it does not request or create a WorkflowExecution directly. Work intake admits and routes the request; the Agent System consumes the accepted work request and is the sole owner of selecting a Workflow version and creating the WorkflowExecution. Ordinary agent interactions do not require this handoff. | | Gateway `TaskController` and `ChatTaskStatus` | `internal/gateway/tasks.go` | WorkflowExecution commands and query view | Approve, cancel, and status use Agent System contracts. Channel code does not duplicate lifecycle constants or decide transitions. | @@ -315,8 +316,8 @@ implemented in different packages: configuration plus forge, store, worktree, agent, event bus, logging, memory, guardrails, skills, and scratch state. - Lifecycle changes occur in both daemon and workflow code. -- In-process and container execution place workflow orchestration on different - sides of the process boundary. +- Workflow orchestration runs inside task-scoped agent containers while the + daemon retains lifecycle, admission, and authority-bearing RPC ownership. - Forge-backed and chat-created work share one record through source flags and synthetic issue numbers. - Repository labels currently select workflows and mirror task state, coupling diff --git a/docs/architecture/migration-decisions.md b/docs/architecture/migration-decisions.md index 439c742db..0b553a34d 100644 --- a/docs/architecture/migration-decisions.md +++ b/docs/architecture/migration-decisions.md @@ -171,19 +171,18 @@ and tests must decide: Conversation branches do not create another memory scope. A memory action has the same scoped effect regardless of which Conversation originated it. -### 6. Runtime and process boundaries +### 6. Runtime and process boundaries — DECIDED -The migration must decide which current execution paths survive: +`archied` is the native resident orchestration and interactive-chat process. +Every autonomous repository workflow crosses one full-task core-NATS handoff +into a task-scoped `archie-agent` container. Embedded versus external NATS +changes broker deployment only; it never selects an executor. The former host +in-process runner, per-stage NATS protocol, and subprocess runner are removed. -- in-process execution; -- `archie-agent` subprocess execution; -- NATS worker execution; -- container isolation; -- forge, store, and worktree RPC services. - -The source architecture remains a modular monolith. A retained process boundary -requires a concrete security-isolation, failure-containment, scaling, or -operational justification. Possible future extraction is insufficient. +Forge, store, and worktree authority remains in `archied` and is exposed to the +task container through scoped RPC services. The worker runs the workflow and +its worker-local ai-sdk loop; it does not receive forge credentials or direct +store access. See `docs/prds/embedded-nats.md`. ### 7. Shared mechanics diff --git a/docs/architecture/observability.md b/docs/architecture/observability.md index 171975e59..3fd8bb9ac 100644 --- a/docs/architecture/observability.md +++ b/docs/architecture/observability.md @@ -10,10 +10,8 @@ rotating file sink, a live `Feed` the dashboard subscribes to, and a reader the `/api/logs` endpoint serves from. Before this implementation, none of that reached inside a task. -A task's actual work happens in an `archie-agent` container, dispatched over -NATS (`[agent] mode = "nats"` is the only supported mode; the in-process -runner exists for tests and is being migrated away — see -[Decision: no new functionality on non-NATS transports](#decision-no-new-functionality-on-non-nats-transports)). +A task's actual work happens in a task-scoped `archie-agent` container, +dispatched as one complete workflow over NATS. Before this design was implemented, five things destroyed the evidence of what that container did: @@ -51,18 +49,14 @@ intended to be usable by people other than the original operator. A system that is only debuggable by an operator who happens to be watching `docker ps` in real time does not meet that bar. -## Decision: NATS is the only transport this feature targets +## Decision: NATS is the sole autonomous handoff -`[agent] mode = "nats"` is the supported deployment; the agent image must -already be able to reach NATS in every deployment, because it is the *only* -channel carrying stage results back to the daemon — if it can't reach NATS, -the task cannot complete regardless of logging. The in-process runner -(`agentexec.InProcessRunner`) exists for tests and is being migrated away. -New functionality is NOT added to it or to any non-NATS path. A container +The agent image must reach NATS in every deployment, because the broker is the +only autonomous task handoff and the only channel carrying task results back +to the daemon. `archied` has no workflow runner or host fallback. A container that dies before establishing a NATS connection is a distinct, narrower -failure (connectivity/config) from the one this document addresses (a -connected container's own output being unrecoverable), and is out of scope -here. +failure (connectivity/config) from the one this document addresses (a connected +container's own output being unrecoverable), and is out of scope here. ## Implemented design @@ -94,9 +88,8 @@ fail the run it is reporting on. ### Daemon side -`cmd/archied/main.go` currently registers `subscribeSystemLogs` once at -startup for the `.system` suffix of `agentexec.SubjectAgentWildcard` -(`"archie.agent.>"`). It demultiplexes by task ID, appends to that task's +`cmd/archied/main.go` registers `subscribeSystemLogs` once at startup on +`agentexec.SubjectSystemWildcard`. It demultiplexes by task ID, appends to that task's sink, and publishes into the existing `logging.Feed` so live task output appears on the dashboard exactly like daemon output. The approved target is for this composition to move to `internal/app/archied`; that package does not diff --git a/docs/prds/adversarial-self-review.md b/docs/prds/adversarial-self-review.md index 1fa09fa72..87aafb1c8 100644 --- a/docs/prds/adversarial-self-review.md +++ b/docs/prds/adversarial-self-review.md @@ -1,9 +1,18 @@ # Adversarial self-review stage -- decision -**Status:** Decided, not yet implemented +**Status:** Superseded; requires redesign before implementation **Date:** 2026-08-22 **Beads issue:** `archie-core-h019.1`, blocks `h019.2/.3/.4/.5` +> **Superseded 2026-08-24 by the full-task worker boundary.** This document is +> retained as the record of the earlier decision, not as an implementation +> contract. It assumes daemon-owned in-process execution and a daemon-side +> second `Pool.Acquire`; both call sites were removed by `archie-core-q15y`. +> The still-useful findings and lifecycle decisions below do not authorize an +> implementation. The feature must first decide how a fresh reviewer receives +> an isolated snapshot from inside the existing task-scoped worker without +> creating a host executor or a nested container lifecycle. + Answers the five questions in `h019.1`'s description against the actual implement workflow, not designed from scratch: the gate pattern, the container pool, and the workflow engine's `Outcome` mechanism already answer diff --git a/internal/agentexec/architecture_test.go b/internal/agentexec/architecture_test.go new file mode 100644 index 000000000..22c40e270 --- /dev/null +++ b/internal/agentexec/architecture_test.go @@ -0,0 +1,58 @@ +package agentexec + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "strings" + "testing" +) + +// The task-scoped archie-agent process owns the workflow and its local model +// loop. agentexec therefore contains the worker-local stage runner, never a +// second process boundary or a stage transport that archied can select. +func TestPackageContainsNoLegacyExecutionModes(t *testing.T) { + forbidden := map[string]bool{ + "InProcessRunner": true, + "NewInProcessRunner": true, + "SubprocessRunner": true, + "NATSRunner": true, + "ServeOne": true, + "Invocation": true, + "AgentRequestMessage": true, + "AgentResponseEnvelope": true, + "StageMessage": true, + "StageConsumer": true, + } + files, err := filepath.Glob("*.go") + if err != nil { + t.Fatal(err) + } + fileset := token.NewFileSet() + for _, path := range files { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, parseErr := parser.ParseFile(fileset, path, nil, 0) + if parseErr != nil { + t.Errorf("parse %s: %v", path, parseErr) + continue + } + for _, declaration := range file.Decls { + switch declaration := declaration.(type) { + case *ast.GenDecl: + for _, spec := range declaration.Specs { + typeSpec, ok := spec.(*ast.TypeSpec) + if ok && forbidden[typeSpec.Name.Name] { + t.Errorf("%s declares legacy execution type %s", fileset.Position(typeSpec.Pos()), typeSpec.Name.Name) + } + } + case *ast.FuncDecl: + if declaration.Recv == nil && forbidden[declaration.Name.Name] { + t.Errorf("%s declares legacy execution constructor %s", fileset.Position(declaration.Pos()), declaration.Name.Name) + } + } + } + } +} diff --git a/internal/agentexec/inprocess.go b/internal/agentexec/loop_runner.go similarity index 94% rename from internal/agentexec/inprocess.go rename to internal/agentexec/loop_runner.go index bd29eb4f4..4a18ccdf6 100644 --- a/internal/agentexec/inprocess.go +++ b/internal/agentexec/loop_runner.go @@ -21,18 +21,16 @@ import ( // Runner executes one autonomous stage against an already prepared workspace. type Runner interface { - // report, when non-nil, is notified once per completed tool call. Only - // a runner executing in the same process as its tools (InProcessRunner) - // can populate it; others accept and ignore it. + // report, when non-nil, is notified once per completed tool call. Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) } type loopFunc func(context.Context, agentloop.Config) (agentloop.Result, error) -// InProcessRunner preserves the current execution behavior behind the v1 -// agent protocol. It is replaced by a subprocess or container runner without -// changing workflow orchestration. -type InProcessRunner struct { +// LoopRunner executes one workflow stage through ai-sdk's agent loop. It is +// worker-local: archie-agent owns the complete workflow and uses this runner +// for each stage inside its task-scoped container. +type LoopRunner struct { runtime *runtime.Runtime log *slog.Logger run loopFunc @@ -43,12 +41,12 @@ type InProcessRunner struct { Limits ToolLimits } -func NewInProcessRunner( +func NewLoopRunner( rt *runtime.Runtime, log *slog.Logger, registries ...*tools.Registry, -) *InProcessRunner { - runner := &InProcessRunner{runtime: rt, log: log, run: agentloop.Run} +) *LoopRunner { + runner := &LoopRunner{runtime: rt, log: log, run: agentloop.Run} if len(registries) > 0 { runner.tools = registries[0] } @@ -67,7 +65,7 @@ func NewInProcessRunner( // it is not configurable. const workspaceToolset = "workspace" -func (r *InProcessRunner) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) { +func (r *LoopRunner) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) { if err := req.Validate(); err != nil { return Result{}, err } @@ -194,7 +192,7 @@ func pluginToolSet(req Request, workspace string, occupied ...core.ToolSet) (cor return set, nil } -func (r *InProcessRunner) logger(req Request) *slog.Logger { +func (r *LoopRunner) logger(req Request) *slog.Logger { if r.log == nil { return slog.New(slog.DiscardHandler) } diff --git a/internal/agentexec/inprocess_test.go b/internal/agentexec/loop_runner_test.go similarity index 95% rename from internal/agentexec/inprocess_test.go rename to internal/agentexec/loop_runner_test.go index bebaf674f..704ac9cb0 100644 --- a/internal/agentexec/inprocess_test.go +++ b/internal/agentexec/loop_runner_test.go @@ -57,8 +57,8 @@ func TestPluginToolSetRejectsAgentLoopCollisions(t *testing.T) { } } -func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) { - runner := &InProcessRunner{ +func TestLoopRunnerMapsRequestAndCapturesOutput(t *testing.T) { + runner := &LoopRunner{ runtime: runtime.NewRuntime(runtime.Config{}), run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) { if cfg.WorkDir != "/workspace" || cfg.ModelRef != "provider/model" || cfg.Mission != "mission" { @@ -103,7 +103,7 @@ func TestInProcessRunnerMapsRequestAndCapturesOutput(t *testing.T) { } } -func TestInProcessRunnerIncludesAvailableCentralTools(t *testing.T) { +func TestLoopRunnerIncludesAvailableCentralTools(t *testing.T) { registry := tools.NewRegistry() if err := registry.Register(tools.ToolEntry{ Name: "memory_search", @@ -113,7 +113,7 @@ func TestInProcessRunnerIncludesAvailableCentralTools(t *testing.T) { }); err != nil { t.Fatal(err) } - runner := &InProcessRunner{ + runner := &LoopRunner{ runtime: runtime.NewRuntime(runtime.Config{}), tools: registry, run: func(ctx context.Context, cfg agentloop.Config) (agentloop.Result, error) { @@ -144,7 +144,7 @@ func TestInProcessRunnerIncludesAvailableCentralTools(t *testing.T) { } } -func TestInProcessRunnerRejectsInvalidCentralToolSchemas(t *testing.T) { +func TestLoopRunnerRejectsInvalidCentralToolSchemas(t *testing.T) { registry := tools.NewRegistry() if err := registry.Register(tools.ToolEntry{ Name: "invalid", @@ -155,7 +155,7 @@ func TestInProcessRunnerRejectsInvalidCentralToolSchemas(t *testing.T) { }); err != nil { t.Fatal(err) } - runner := &InProcessRunner{ + runner := &LoopRunner{ runtime: runtime.NewRuntime(runtime.Config{}), tools: registry, run: func(context.Context, agentloop.Config) (agentloop.Result, error) { @@ -280,10 +280,10 @@ func TestMergeToolSetsLaterWinsOnCollision(t *testing.T) { } } -func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) { +func TestLoopRunnerPreservesCallerCancellation(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - runner := &InProcessRunner{ + runner := &LoopRunner{ runtime: runtime.NewRuntime(runtime.Config{}), run: func(context.Context, agentloop.Config) (agentloop.Result, error) { return agentloop.Result{Status: agentloop.StatusParked, StopReason: agentloop.StopTimedOut}, nil @@ -301,8 +301,8 @@ func TestInProcessRunnerPreservesCallerCancellation(t *testing.T) { // tool handler discards the incoming context (the handler is declared as // func(_ context.Context, input string) and calls skillscript.Run without // forwarding ctx). Every other execution path in archie-core respects -// context cancellation (SubprocessRunner uses exec.CommandContext, -// InProcessRunner checks context.Cause), but a cancelled/timed-out context +// context cancellation (LoopRunner checks context.Cause), but a +// cancelled/timed-out context // has zero effect on run_go_script — a blocking script wedges the // goroutine permanently. func TestScriptToolHonorsContextCancellation(t *testing.T) { diff --git a/internal/agentexec/nats.go b/internal/agentexec/nats.go deleted file mode 100644 index 6d6247c8d..000000000 --- a/internal/agentexec/nats.go +++ /dev/null @@ -1,136 +0,0 @@ -package agentexec - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "log/slog" - "time" - - "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/eventbus" -) - -// AgentRequestMessage is the NATS payload for an agent stage execution request. -// When Workflow is set and Stages is populated, the agent runs all stages as a -// per-task batch rather than a single stage. PRD §1. -type AgentRequestMessage struct { - TaskID int64 `json:"task_id"` - Attempt int `json:"attempt"` - Stage string `json:"stage"` - Workflow string `json:"workflow,omitempty"` - Channel string `json:"channel,omitempty"` // "response" (default) or "system" - Workspace string `json:"workspace"` - Request Request `json:"request"` - Stages []Request `json:"stages,omitempty"` // batch: all agent stages for this task - Providers map[string]Provider `json:"providers,omitempty"` - // MCPServers carries MCP server definitions so the agent can construct - // transports, discover tools, and register them locally. Absent/empty - // means no MCP servers (backward compatible). - MCPServers []config.MCPServer `json:"mcp_servers,omitempty"` -} - -// AgentResponseEnvelope is the response payload published to the reply inbox. -type AgentResponseEnvelope struct { - Version int `json:"version"` - Result Result `json:"result"` - Error string `json:"error,omitempty"` - Channel string `json:"channel,omitempty"` // "response" (default) or "system" - TaskCompleted bool `json:"task_completed,omitempty"` // true when all stages finished (per-task mode) -} - -const defaultAgentTimeout = 30 * time.Minute - -// RequestBus is the messaging this runner needs: publish a request carrying a -// reply address, and create the inbox that address points at. -// -// Declared here rather than taking eventbus.Bus because a domain defines the -// smallest interface required to do its work -- this runner never fetches or -// subscribes, and should not be able to. -type RequestBus interface { - PublishRequest(ctx context.Context, subject, replyTo string, payload []byte) error - NewReplyInbox() (eventbus.ReplyInbox, error) -} - -// NATSRunner sends agent stage execution requests over the bus and waits for -// replies on a one-shot inbox. It implements Runner. -// -// The name is historical: it holds no NATS type and works with any bus -// satisfying RequestBus. -type NATSRunner struct { - Bus RequestBus - Providers map[string]Provider - MCPServers []config.MCPServer - Log *slog.Logger -} - -// Run publishes a stage execution request to JetStream with an X-Archie-Reply -// header, blocks on the sync inbox subscription, and returns the result. -// -// report is ignored: execution happens on whatever remote worker answers the -// request, a different process with no way to call back here per tool call. -func (r *NATSRunner) Run(ctx context.Context, workspace string, req Request, _ ToolCallReporter) (Result, error) { - if err := req.Validate(); err != nil { - return Result{}, err - } - - // 1. Create reply inbox with auto-unsubscribe after one message. - replySub, err := r.Bus.NewReplyInbox() - if err != nil { - return Result{}, fmt.Errorf("nats reply inbox: %w", err) - } - defer func() { - if err := replySub.Close(); err != nil { - r.Log.Warn("reply inbox close failed", "err", err) - } - }() - - // 2. Compute timeout from budget. - timeout := defaultAgentTimeout - if req.Budget.WallClock > 0 { - timeout = req.Budget.WallClock - } - - // 3. Publish request with reply header. - msg := AgentRequestMessage{ - TaskID: req.TaskID, - Attempt: req.Attempt, - Stage: req.Stage, - Workflow: req.Workflow, - Workspace: workspace, - Request: req, - Providers: r.Providers, - MCPServers: r.MCPServers, - } - data, err := json.Marshal(msg) - if err != nil { - return Result{}, err - } - - subject := SubjectForRequest(req.TaskID) - if err := r.Bus.PublishRequest(ctx, subject, replySub.Subject(), data); err != nil { - return Result{}, fmt.Errorf("publish agent request: %w", err) - } - - // 4. Wait for reply (blocking, matching SubprocessRunner.Run behaviour). - replyCtx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - reply, err := replySub.Next(replyCtx) - if err != nil { - return Result{}, fmt.Errorf("agent reply: %w", err) - } - - // 5. Decode response. - var envelope AgentResponseEnvelope - if err := json.Unmarshal(reply, &envelope); err != nil { - return Result{}, fmt.Errorf("decode agent response: %w", err) - } - if envelope.Error != "" { - return envelope.Result, errors.New(envelope.Error) - } - if err := envelope.Result.ValidateFor(req); err != nil { - return envelope.Result, err - } - return envelope.Result, nil -} diff --git a/internal/agentexec/nats_test.go b/internal/agentexec/nats_test.go deleted file mode 100644 index 92407e344..000000000 --- a/internal/agentexec/nats_test.go +++ /dev/null @@ -1,285 +0,0 @@ -package agentexec - -import ( - "context" - "encoding/json" - "log/slog" - "testing" - - "github.com/nats-io/nats-server/v2/server" - natssrv "github.com/nats-io/nats-server/v2/test" - - "github.com/samcharles93/archie-core/internal/domain/workintake" - "github.com/samcharles93/archie-core/internal/eventbus" - arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" -) - -// ── helpers ────────────────────────────────────────────────────────── - -type mockRunner struct{} - -func (m *mockRunner) Run(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) { - return Result{ - Version: ProtocolVersion, - TaskID: req.TaskID, - Attempt: req.Attempt, - Stage: req.Stage, - Status: StatusPassed, - Summary: "mock:" + req.Mission, - TokensUsed: 10, - Iterations: 1, - }, nil -} - -var mockFactory = func(providers map[string]Provider, log *slog.Logger) Runner { - return &mockRunner{} -} - -// ── regression: Gap 1 -- per-task agent ────────────────────────────── - -func TestHandleMessageReadsWorkflowField(t *testing.T) { - // Gap 1: archie-agent is per-stage, not per-task. - // PRD section 1: when the daemon sends a task-level message with - // Workflow="implement" and Stages populated, the agent must run all - // stages as a batch. Single-stage mode (Request only) is the - // backward-compatible fallback. - - ws := t.TempDir() - providers := map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}} - - // Single-stage mode: uses Request, no Workflow, no Stages. - singleMsg := AgentRequestMessage{ - TaskID: 1, - Attempt: 1, - Stage: "plan", - Workspace: ws, - Request: Request{ - Version: ProtocolVersion, TaskID: 1, Attempt: 1, - Stage: "plan", Model: "test/model", Mission: "single", - Budget: Budget{MaxSteps: 1}, - }, - Providers: providers, - } - mockFactory := func(providers map[string]Provider, log *slog.Logger) Runner { - return &mockRunner{} - } - singleResp, err := HandleMessage(context.Background(), singleMsg, slog.New(slog.DiscardHandler), mockFactory) - if err != nil { - t.Fatal(err) - } - if singleResp.TaskCompleted { - t.Error("single-stage mode set TaskCompleted=true -- should be false") - } - - // Per-task mode: Workflow set, Stages populated with two stages. - multiMsg := AgentRequestMessage{ - TaskID: 2, - Attempt: 1, - Stage: "plan", - Workflow: "implement", - Workspace: ws, - Request: Request{ - Version: ProtocolVersion, TaskID: 2, Attempt: 1, - Stage: "plan", Model: "test/model", Mission: "multi-1", - Budget: Budget{MaxSteps: 1}, - }, - Stages: []Request{ - { - Version: ProtocolVersion, TaskID: 2, Attempt: 1, - Stage: "plan", Model: "test/model", Mission: "multi-plan", - Budget: Budget{MaxSteps: 1}, - }, - { - Version: ProtocolVersion, TaskID: 2, Attempt: 1, - Stage: "build", Model: "test/model", Mission: "multi-build", - Budget: Budget{MaxSteps: 1}, - }, - }, - Providers: providers, - } - multiResp, err := HandleMessage(context.Background(), multiMsg, slog.New(slog.DiscardHandler), mockFactory) - if err != nil { - t.Fatal(err) - } - if !multiResp.TaskCompleted { - t.Error("Gap 1: per-task mode did not set TaskCompleted=true. " + - "The agent must signal task completion when all stages in a " + - "workflow batch have been processed.") - } - // Batch results must aggregate from both stages. - if multiResp.Result.TokensUsed == singleResp.Result.TokensUsed && - multiResp.Result.Iterations == singleResp.Result.Iterations { - t.Error("Gap 1: per-task mode produced same token/iteration counts " + - "as single-stage mode. Multi-stage batch must accumulate " + - "results from all stages. See PRD section 1.") - } -} - -// ── regression: Gap 3 -- response/system channel split ─────────────── - -func TestHandleMessageRoutesSystemMessagesSeparately(t *testing.T) { - // Gap 3: no response/system channel split. - // PRD section 2: system messages go to archie.agent..system and - // are never forwarded to humans. Response messages go to - // archie.agent..response for daemon review before human delivery. - // Currently HandleMessage always returns Channel="response" -- there - // is no code path that produces a system-channel response. - - msg := AgentRequestMessage{ - TaskID: 1, - Attempt: 1, - Stage: "plan", - Workspace: t.TempDir(), - Request: Request{ - Version: ProtocolVersion, - TaskID: 1, - Attempt: 1, - Stage: "plan", - Model: "test/model", - Mission: "test", - Budget: Budget{MaxSteps: 1}, - }, - Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}, - } - - // Normal stage request -- should route to response channel. - resp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory) - if err != nil { - t.Fatal(err) - } - if resp.Channel != "response" { - t.Errorf("normal stage request: Channel = %q, want \"response\"", resp.Channel) - } - - // System message (health check, log dump request) -- should route to - // system channel. Currently HandleMessage always returns "response". - // The daemon sets Channel on the request to indicate message type. - msg.Channel = "system" - sysResp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), mockFactory) - if err != nil { - t.Fatal(err) - } - if sysResp.Channel != "system" { - t.Error("Gap 3: HandleMessage ignores the input Channel field. " + - "When the daemon sends a system message (Channel=\"system\"), " + - "the response must be routed to archie.agent..system, " + - "not to the reply inbox. Currently all responses go to the " + - "same inbox regardless of channel. See PRD section 2.") - } - - // Verify the subject functions exist and are distinct. - respSubj := SubjectForResponse(42) - sysSubj := SubjectForSystem(42) - if respSubj == sysSubj || respSubj == "" || sysSubj == "" { - t.Error("Gap 3: subject functions broken -- verify SubjectForAgentResponse " + - "and SubjectForAgentSystem return distinct, non-empty subjects.") - } -} - -// ── existing tests ─────────────────────────────────────────────────── - -func startEmbeddedNATS(t *testing.T) *server.Server { - t.Helper() - srv := natssrv.RunRandClientPortServer() - t.Cleanup(srv.Shutdown) - if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: t.TempDir()}); err != nil { - t.Fatalf("enable jetstream: %v", err) - } - return srv -} - -func startHandler(t *testing.T, client *arnats.Client) { - t.Helper() - ctx, cancel := context.WithCancel(context.Background()) - t.Cleanup(cancel) - - // Drain the client's own consumer rather than subscribing a second one: - // the stream uses work-queue retention, so two consumers with - // overlapping filter subjects conflict. This mirrors archie-agent. - go func() { - for ctx.Err() == nil { - msg, err := client.Fetch(ctx) - if err != nil { - continue - } - if err := replyToStage(ctx, client, msg); err != nil { - t.Errorf("stage handler: %v", err) - _ = msg.Nak() - continue - } - _ = msg.Ack() - } - }() -} - -// replyToStage answers one stage request with a canned passing result. -func replyToStage(ctx context.Context, client *arnats.Client, msg eventbus.Message) error { - var req AgentRequestMessage - if err := json.Unmarshal(msg.Data(), &req); err != nil { - return err - } - replyTo, err := msg.ReplyAddress() - if err != nil { - return err - } - data, err := json.Marshal(AgentResponseEnvelope{ - Version: req.Request.Version, - Result: Result{ - Version: ProtocolVersion, - TaskID: req.TaskID, - Attempt: req.Attempt, - Stage: req.Stage, - Status: StatusPassed, - Summary: "handler-reply", - TokensUsed: 42, - }, - }) - if err != nil { - return err - } - return client.Respond(ctx, replyTo, data) -} - -func TestNATSRunnerRoundTrip(t *testing.T) { - srv := startEmbeddedNATS(t) - url := srv.ClientURL() - - ctx := context.Background() - client, err := arnats.Connect(ctx, arnats.Config{URL: url, Subjects: []string{workintake.SubjectTaskWildcard, SubjectAgentWildcard}, FilterSubject: SubjectAgentWildcard}, slog.New(slog.DiscardHandler)) - if err != nil { - t.Fatal(err) - } - defer client.Close() - - startHandler(t, client) - - runner := &NATSRunner{ - Bus: client, - Providers: map[string]Provider{"openai": {Class: "openai", APIKeyEnv: "TEST_KEY"}}, - Log: slog.New(slog.DiscardHandler), - } - - req := Request{ - Version: ProtocolVersion, - TaskID: 42, - Attempt: 1, - Stage: "test", - Model: "openai/gpt", - Mission: "test mission", - Budget: Budget{MaxSteps: 5}, - } - - result, err := runner.Run(ctx, "/tmp/test-workspace", req, nil) - if err != nil { - t.Fatal(err) - } - if result.Status != StatusPassed { - t.Fatalf("expected passed, got %s", result.Status) - } - if result.Summary != "handler-reply" { - t.Fatalf("expected 'handler-reply', got %q", result.Summary) - } - if result.TokensUsed != 42 { - t.Fatalf("expected 42 tokens, got %d", result.TokensUsed) - } -} diff --git a/internal/agentexec/protocol.go b/internal/agentexec/protocol.go index eb332b9c1..a6775288a 100644 --- a/internal/agentexec/protocol.go +++ b/internal/agentexec/protocol.go @@ -1,13 +1,12 @@ -// Package agentexec defines the unprivileged agent execution boundary. -// Workflow orchestration and external side effects remain daemon-owned. +// Package agentexec defines worker-local workflow-stage execution. archie-agent +// owns workflow orchestration; authority-bearing forge, store, and push effects +// remain daemon-owned behind scoped RPC boundaries. package agentexec import ( "encoding/json" "errors" "fmt" - "net/url" - "strings" "time" ) @@ -133,59 +132,6 @@ type Provider struct { BaseURL string `json:"base_url,omitempty"` } -func (p Provider) validate() error { - if strings.TrimSpace(p.Class) == "" { - return fmt.Errorf("provider class is required") - } - if p.BaseURL == "" { - return nil - } - u, err := url.Parse(p.BaseURL) - if err != nil { - return fmt.Errorf("parse provider base_url: %w", err) - } - if u.User != nil || u.RawQuery != "" || u.Fragment != "" { - return fmt.Errorf("provider base_url must not contain userinfo, query parameters, or a fragment") - } - return nil -} - -// Invocation is the single request accepted by archie-agent on stdin. -type Invocation struct { - Version int `json:"version"` - Workspace string `json:"workspace"` - Request Request `json:"request"` - Providers map[string]Provider `json:"providers"` -} - -// Validate rejects invocations that cannot be executed safely. -func (i Invocation) Validate() error { - if i.Version != ProtocolVersion { - return fmt.Errorf("agent invocation protocol version %d is unsupported (want %d)", i.Version, ProtocolVersion) - } - if i.Workspace == "" { - return fmt.Errorf("agent invocation workspace is required") - } - if len(i.Providers) == 0 { - return fmt.Errorf("agent invocation providers are required") - } - for name, provider := range i.Providers { - if err := provider.validate(); err != nil { - return fmt.Errorf("agent invocation provider %q: %w", name, err) - } - } - return i.Request.Validate() -} - -// Response is the single envelope written by archie-agent on stdout. -// Error carries execution errors after the worker successfully decoded the -// invocation; process-level protocol failures use a non-zero exit status. -type Response struct { - Version int `json:"version"` - Result Result `json:"result"` - Error string `json:"error,omitempty"` -} - // ValidateFor rejects incompatible or misrouted results before the daemon // applies them to task state. func (r Result) ValidateFor(req Request) error { diff --git a/internal/agentexec/runtime.go b/internal/agentexec/runtime.go index 1833f0c68..c337d7286 100644 --- a/internal/agentexec/runtime.go +++ b/internal/agentexec/runtime.go @@ -2,8 +2,8 @@ package agentexec import "github.com/samcharles93/ai-sdk/runtime" -// NewRuntime builds the provider runtime shared by archied's in-process mode -// and the archie-agent worker. Nil means no providers were configured. +// NewRuntime builds a provider runtime for interactive chat or a worker-local +// workflow stage. Nil means no providers were configured. func NewRuntime(providers map[string]Provider) *runtime.Runtime { if len(providers) == 0 { return nil diff --git a/internal/agentexec/skill_test.go b/internal/agentexec/skill_test.go deleted file mode 100644 index 517cbcc69..000000000 --- a/internal/agentexec/skill_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package agentexec - -import ( - "context" - "log/slog" - "os" - "path/filepath" - "testing" -) - -// captureRunner records the Request it receives for test assertions. -type captureRunner struct { - callback func(Request) -} - -func (c *captureRunner) Run(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) { - c.callback(req) - return Result{ - Version: ProtocolVersion, - TaskID: req.TaskID, - Attempt: req.Attempt, - Stage: req.Stage, - Status: StatusPassed, - Summary: "done", - TokensUsed: 1, - }, nil -} - -// ── regression: HandleMessage must not duplicate skill body ───────── - -func TestHandleMessageDoesNotDuplicateSkillBody(t *testing.T) { - // Regression for issue #65: the daemon already prepends the skill - // body to every mission via missionWithSkill() before the Request - // reaches HandleMessage. HandleMessage must pass the mission - // through unchanged -- a second prepend here would duplicate the - // skill body in the agent's context window. - - dir := t.TempDir() - skillsDir := filepath.Join(dir, ".agents", "skills", "archie-wf-tdd") - if err := os.MkdirAll(skillsDir, 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(filepath.Join(skillsDir, "SKILL.md"), []byte(`--- -name: archie-wf-tdd -description: TDD bugfix workflow -version: 1.0.0 -metadata: - archie: - workflow: tdd ---- -Analyse the bug. Write repro tests. Fix. -`), 0o644); err != nil { - t.Fatal(err) - } - - // Mission already includes the daemon-side prepend (as produced by - // missionWithSkill in internal/workflow/agent.go). - alreadyPrepended := "Follow these project-specific guidelines:\n\n" + - "Analyse the bug. Write repro tests. Fix.\n\n---\n\n" + - "Analyse this bug" - - var capturedMission string - captureFactory := func(providers map[string]Provider, log *slog.Logger) Runner { - return &captureRunner{callback: func(req Request) { - capturedMission = req.Mission - }} - } - - msg := AgentRequestMessage{ - TaskID: 1, - Attempt: 1, - Stage: "analyse", - Workflow: "tdd", - Workspace: dir, - Request: Request{ - Version: ProtocolVersion, TaskID: 1, Attempt: 1, - Stage: "analyse", Model: "test/model", - Mission: alreadyPrepended, - Budget: Budget{MaxSteps: 1}, - }, - Providers: map[string]Provider{"test": {Class: "openai", APIKeyEnv: "FAKE"}}, - } - - resp, err := HandleMessage(context.Background(), msg, slog.New(slog.DiscardHandler), captureFactory) - if err != nil { - t.Fatal(err) - } - _ = resp - - // The mission must be passed through unchanged. Any modification - // would indicate a double-prepend bug (issue #65). - if capturedMission != alreadyPrepended { - t.Errorf("HandleMessage modified the mission:\n got: %q\n want: %q\n\n"+ - "The daemon already prepends the skill body via missionWithSkill(). "+ - "HandleMessage must not prepend it again -- doing so duplicates content "+ - "in the agent's context window (issue #65).", - capturedMission, alreadyPrepended) - } -} diff --git a/internal/agentexec/stage_message.go b/internal/agentexec/stage_message.go deleted file mode 100644 index b80552de8..000000000 --- a/internal/agentexec/stage_message.go +++ /dev/null @@ -1,19 +0,0 @@ -package agentexec - -import "context" - -// StageMessage is one decoded single-stage request together with the transport -// operations that complete its delivery. Infrastructure owns the wire payload, -// reply inbox, and acknowledgement mechanism; the worker only sees typed data. -type StageMessage interface { - Request() (AgentRequestMessage, error) - Respond(context.Context, *AgentResponseEnvelope) error - Ack() error - Nak() error - LogAttributes() []any -} - -// StageConsumer receives decoded single-stage requests. -type StageConsumer interface { - FetchStage(context.Context) (StageMessage, error) -} diff --git a/internal/agentexec/subjects.go b/internal/agentexec/subjects.go index 65dcfa0cd..7fecbd3df 100644 --- a/internal/agentexec/subjects.go +++ b/internal/agentexec/subjects.go @@ -5,20 +5,14 @@ import ( "strings" ) -// Agent execution subjects. +// Agent observability subjects. // // These belong to this package because it defines what an agent request and // response mean. They previously sat in the NATS package, which made the // transport the owner of Archie's agent protocol; see // docs/architecture/dependencies-and-contracts.md -- message schemas and the // subjects addressing them stay with the domain that defines them. -// -// The stage travels in the payload, not the subject: one subject per task -// carrying sequential stage messages. const ( - // SubjectAgentWildcard matches every agent subject. - SubjectAgentWildcard = "archie.agent.>" - // SubjectSystemWildcard matches every task's system subject, for a // daemon subscribing to all of them at once with a single core NATS // subscription rather than one per running task. @@ -34,19 +28,6 @@ const ( subjectEventsSuffix = ".events" ) -// SubjectForRequest returns the subject carrying stage execution requests for -// a task. -func SubjectForRequest(taskID int64) string { - return subjectForTask(taskID, "request") -} - -// SubjectForResponse returns the subject for agent output destined for human -// channels. The daemon reviews these before forwarding to issue comments, -// labels, or pull requests. -func SubjectForResponse(taskID int64) string { - return subjectForTask(taskID, "response") -} - // SubjectForSystem returns the subject for internal agent messages such as // log dumps, health, and PII warnings. The daemon reads these for // observability and never forwards them. diff --git a/internal/agentexec/subprocess.go b/internal/agentexec/subprocess.go deleted file mode 100644 index e0dbb5232..000000000 --- a/internal/agentexec/subprocess.go +++ /dev/null @@ -1,170 +0,0 @@ -package agentexec - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "os/exec" - "strings" -) - -const maxDiagnosticBytes = 64 << 10 - -// SubprocessRunner executes each agent stage in a fresh archie-agent process. -type SubprocessRunner struct { - Command string - Args []string - // Environ is the daemon environment to select from. AdditionalEnv names - // operator-approved compatibility variables; the requested provider's key - // variable is added automatically for that invocation only. - Environ []string - AdditionalEnv []string - Diagnostics io.Writer - Providers map[string]Provider -} - -// Run ignores report: the subprocess executes tools in its own process, so -// there is nothing here to observe a call as it happens. -func (r *SubprocessRunner) Run(ctx context.Context, workspace string, req Request, _ ToolCallReporter) (Result, error) { - providerName, _, ok := strings.Cut(req.Model, "/") - if !ok || providerName == "" { - return Result{}, fmt.Errorf("agent model %q must be provider/model", req.Model) - } - provider, ok := r.Providers[providerName] - if !ok { - return Result{}, fmt.Errorf("agent model provider %q is not configured", providerName) - } - providers := map[string]Provider{providerName: provider} - invocation := Invocation{Version: ProtocolVersion, Workspace: workspace, Request: req, Providers: providers} - if err := invocation.Validate(); err != nil { - return Result{}, err - } - if strings.TrimSpace(r.Command) == "" { - return Result{}, fmt.Errorf("archie-agent command is required") - } - payload, err := json.Marshal(invocation) - if err != nil { - return Result{}, fmt.Errorf("encode invocation: %w", err) - } - payload = append(payload, '\n') - - cmd := exec.CommandContext(ctx, r.Command, r.Args...) - configureProcessCancellation(cmd) - cmd.Stdin = bytes.NewReader(payload) - cmd.Env = WorkerEnvironment(r.Environ, r.AdditionalEnv, providers) - stdout := &cappedBuffer{limit: maxProtocolBytes} - stderr := &cappedBuffer{limit: maxDiagnosticBytes} - cmd.Stdout = stdout - cmd.Stderr = stderr - if r.Diagnostics != nil { - cmd.Stderr = io.MultiWriter(r.Diagnostics, stderr) - } - if err := cmd.Run(); err != nil { - if cause := context.Cause(ctx); cause != nil { - if diagnostic := strings.TrimSpace(stderr.String()); diagnostic != "" { - return Result{}, fmt.Errorf("%w: archie-agent: %s", cause, diagnostic) - } - return Result{}, cause - } - return Result{}, fmt.Errorf("archie-agent process: %w: %s", err, strings.TrimSpace(stderr.String())) - } - if stdout.truncated { - return Result{}, fmt.Errorf("archie-agent response exceeds %d bytes", maxProtocolBytes) - } - return decodeSubprocessResponse(bytes.NewReader(stdout.Bytes()), stderr.String(), req) -} - -// decodeSubprocessResponse reads one Response from r and validates it -// against req, returning the Result or an error. -func decodeSubprocessResponse(r io.Reader, stderrText string, req Request) (Result, error) { - var response Response - if err := decodeOne(r, &response); err != nil { - return Result{}, fmt.Errorf("decode archie-agent response: %w: %s", err, strings.TrimSpace(stderrText)) - } - if response.Version != ProtocolVersion { - return Result{}, fmt.Errorf("archie-agent response protocol version %d is unsupported", response.Version) - } - if response.Result.Version != 0 { - if err := response.Result.ValidateFor(req); err != nil { - return Result{}, err - } - } - if response.Error != "" { - return response.Result, errors.New(response.Error) - } - if err := response.Result.ValidateFor(req); err != nil { - return Result{}, err - } - return response.Result, nil -} - -type cappedBuffer struct { - bytes.Buffer - limit int - truncated bool -} - -func (b *cappedBuffer) Write(p []byte) (int, error) { - original := len(p) - remaining := b.limit - b.Len() - if remaining <= 0 { - b.truncated = true - return original, nil - } - if len(p) > remaining { - _, _ = b.Buffer.Write(p[:remaining]) - b.truncated = true - return original, nil - } - _, _ = b.Buffer.Write(p) - return original, nil -} - -// SelectEnvironment copies only named variables from environ. Later entries -// win, matching os.Environ and exec.Cmd semantics without accidentally -// inheriting unrelated variables. This is not an OS security boundary: a -// same-UID subprocess may still access daemon-readable host resources. -func SelectEnvironment(environ, names []string) []string { - allowed := make(map[string]bool, len(names)) - for _, name := range names { - if name != "" { - allowed[name] = true - } - } - values := make(map[string]string, len(allowed)) - for _, entry := range environ { - name, _, ok := strings.Cut(entry, "=") - if ok && allowed[name] { - values[name] = entry - } - } - out := make([]string, 0, len(values)) - for _, name := range names { - if entry, ok := values[name]; ok { - out = append(out, entry) - delete(values, name) - } - } - return out -} - -// DefaultEnvironmentNames are compatibility variables safe to forward by -// default. Additional toolchain variables must be explicitly configured. -func DefaultEnvironmentNames() []string { - return []string{"PATH", "HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "SSL_CERT_FILE", "SSL_CERT_DIR"} -} - -// WorkerEnvironment selects the default compatibility variables, configured -// additions, and each provider's API-key variable. Forge credentials are not -// forwarded unless an operator explicitly lists or reuses their variable. -func WorkerEnvironment(environ, additional []string, providers map[string]Provider) []string { - names := DefaultEnvironmentNames() - names = append(names, additional...) - for _, provider := range providers { - names = append(names, provider.APIKeyEnv) - } - return SelectEnvironment(environ, names) -} diff --git a/internal/agentexec/subprocess_process_unix.go b/internal/agentexec/subprocess_process_unix.go deleted file mode 100644 index 39c5350dc..000000000 --- a/internal/agentexec/subprocess_process_unix.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris - -package agentexec - -import ( - "errors" - "os" - "os/exec" - "syscall" -) - -// configureProcessCancellation puts the worker and every command it starts in -// a dedicated process group. CommandContext cancellation then kills the whole -// group so toolchain grandchildren cannot continue mutating the worktree. -func configureProcessCancellation(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - cmd.Cancel = func() error { - if cmd.Process == nil { - return os.ErrProcessDone - } - err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - if errors.Is(err, syscall.ESRCH) { - return os.ErrProcessDone - } - return err - } -} diff --git a/internal/agentexec/subprocess_process_windows.go b/internal/agentexec/subprocess_process_windows.go deleted file mode 100644 index 11c88166b..000000000 --- a/internal/agentexec/subprocess_process_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build windows - -package agentexec - -import "os/exec" - -// Windows keeps exec.CommandContext's direct-process cancellation. Production -// subprocess and container execution are currently supported on Unix hosts. -func configureProcessCancellation(_ *exec.Cmd) {} diff --git a/internal/agentexec/subprocess_test.go b/internal/agentexec/subprocess_test.go deleted file mode 100644 index 8d5b39474..000000000 --- a/internal/agentexec/subprocess_test.go +++ /dev/null @@ -1,249 +0,0 @@ -package agentexec - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestSubprocessRunnerRoundTrip(t *testing.T) { - req := testRequest() - result, err := helperRunner("success").Run(context.Background(), "/workspace", req, nil) - if err != nil { - t.Fatal(err) - } - if result.Summary != "from child" || result.TaskID != req.TaskID || result.Attempt != req.Attempt { - t.Fatalf("result = %#v", result) - } -} - -func TestSubprocessRunnerReturnsStampedWorkerError(t *testing.T) { - req := testRequest() - result, err := helperRunner("worker-error").Run(context.Background(), "/workspace", req, nil) - if err == nil || err.Error() != "provider unavailable" { - t.Fatalf("error = %v", err) - } - if result.TaskID != req.TaskID || result.Stage != req.Stage { - t.Fatalf("partial result lost identity: %#v", result) - } -} - -func TestSubprocessRunnerRejectsMalformedAndOversizedOutput(t *testing.T) { - for _, behavior := range []string{"malformed", "oversized", "multiple", "mismatched"} { - t.Run(behavior, func(t *testing.T) { - _, err := helperRunner(behavior).Run(context.Background(), "/workspace", testRequest(), nil) - if err == nil { - t.Fatal("Run succeeded") - } - }) - } -} - -func TestSubprocessRunnerReportsExitDiagnostics(t *testing.T) { - _, err := helperRunner("exit").Run(context.Background(), "/workspace", testRequest(), nil) - if err == nil || !strings.Contains(err.Error(), "child diagnostic") { - t.Fatalf("error = %v", err) - } -} - -func TestSubprocessRunnerCancelsChild(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - _, err := helperRunner("hang").Run(ctx, "/workspace", testRequest(), nil) - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("error = %v, want deadline exceeded", err) - } -} - -func TestSubprocessRunnerCancellationKillsGrandchildren(t *testing.T) { - marker := filepath.Join(t.TempDir(), "grandchild-survived") - runner := helperRunner("spawn-grandchild") - runner.Environ = append(runner.Environ, "AGENT_HELPER_MARKER="+marker) - runner.AdditionalEnv = append(runner.AdditionalEnv, "AGENT_HELPER_MARKER") - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - _, err := runner.Run(ctx, "/workspace", testRequest(), nil) - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("error = %v, want deadline exceeded", err) - } - time.Sleep(300 * time.Millisecond) - if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) { - t.Fatalf("grandchild survived cancellation: stat error = %v", err) - } -} - -func TestSubprocessRunnerForwardsOnlyRequestedProvider(t *testing.T) { - runner := helperRunner("provider-scope") - runner.Environ = append(runner.Environ, "OTHER_KEY=must-not-leak") - runner.Providers["other"] = Provider{Class: "openai", APIKeyEnv: "OTHER_KEY"} - if _, err := runner.Run(context.Background(), "/workspace", testRequest(), nil); err != nil { - t.Fatal(err) - } -} - -func TestInvocationRejectsCredentialBearingProviderURL(t *testing.T) { - for _, baseURL := range []string{ - "https://token@example.com/v1", - "https://example.com/v1?api_key=secret", - "https://example.com/v1#secret", - } { - t.Run(baseURL, func(t *testing.T) { - invocation := Invocation{ - Version: ProtocolVersion, Workspace: "/workspace", Request: testRequest(), - Providers: map[string]Provider{"provider": {Class: "openai", BaseURL: baseURL}}, - } - if err := invocation.Validate(); err == nil { - t.Fatal("Validate succeeded") - } - }) - } -} - -func TestSelectEnvironmentDoesNotLeakUnlistedValues(t *testing.T) { - got := WorkerEnvironment( - []string{"PATH=/bin", "ARCHIE_GITHUB_TOKEN=secret", "OPENAI_API_KEY=model", "PATH=/usr/bin"}, - nil, - map[string]Provider{"openai": {APIKeyEnv: "OPENAI_API_KEY"}}, - ) - want := []string{"PATH=/usr/bin", "OPENAI_API_KEY=model"} - if strings.Join(got, "\n") != strings.Join(want, "\n") { - t.Fatalf("environment = %v, want %v", got, want) - } -} - -func TestServeOneRejectsMultipleInvocations(t *testing.T) { - input := `{"version":1} {"version":1}` - err := ServeOne(context.Background(), strings.NewReader(input), &strings.Builder{}, nil) - if err == nil || !strings.Contains(err.Error(), "multiple JSON values") { - t.Fatalf("error = %v", err) - } -} - -func TestServeOneWritesStampedExecutionError(t *testing.T) { - invocation := Invocation{ - Version: ProtocolVersion, Workspace: "/workspace", Request: testRequest(), - Providers: map[string]Provider{"provider": {Class: "openai"}}, - } - input, err := json.Marshal(invocation) - if err != nil { - t.Fatal(err) - } - var output strings.Builder - err = serveOne(context.Background(), strings.NewReader(string(input)), &output, func(Invocation) Runner { - return runnerFunc(func(_ context.Context, _ string, req Request, _ ToolCallReporter) (Result, error) { - return Result{ - Version: ProtocolVersion, TaskID: req.TaskID, Attempt: req.Attempt, - Stage: req.Stage, Status: StatusPassed, - }, errors.New("provider unavailable") - }) - }) - if err != nil { - t.Fatal(err) - } - var response Response - if err := json.Unmarshal([]byte(output.String()), &response); err != nil { - t.Fatal(err) - } - if response.Error != "provider unavailable" || response.Result.TaskID != invocation.Request.TaskID { - t.Fatalf("response = %#v", response) - } -} - -func TestDecodeOneRejectsOversizedInput(t *testing.T) { - var value any - err := decodeOne(strings.NewReader(`"`+strings.Repeat("x", maxProtocolBytes)+`"`), &value) - if err == nil || !strings.Contains(err.Error(), "exceeds") { - t.Fatalf("error = %v", err) - } -} - -func helperRunner(behavior string) *SubprocessRunner { - return &SubprocessRunner{ - Command: os.Args[0], Args: []string{"-test.run=TestAgentHelperProcess"}, - Environ: []string{ - "GO_WANT_AGENT_HELPER=1", "AGENT_HELPER_BEHAVIOR=" + behavior, - "PROVIDER_KEY=selected", - }, - AdditionalEnv: []string{"GO_WANT_AGENT_HELPER", "AGENT_HELPER_BEHAVIOR"}, - Providers: map[string]Provider{"provider": {Class: "openai", APIKeyEnv: "PROVIDER_KEY"}}, - } -} - -type runnerFunc func(context.Context, string, Request, ToolCallReporter) (Result, error) - -func (f runnerFunc) Run(ctx context.Context, workspace string, req Request, report ToolCallReporter) (Result, error) { - return f(ctx, workspace, req, report) -} - -func testRequest() Request { - return Request{ - Version: ProtocolVersion, TaskID: 42, Attempt: 3, Stage: "build", - Model: "provider/model", Mission: "test mission", - } -} - -func TestAgentHelperProcess(t *testing.T) { - ctx := t.Context() - - if os.Getenv("GO_WANT_AGENT_HELPER") != "1" { - return - } - var invocation Invocation - if err := json.NewDecoder(os.Stdin).Decode(&invocation); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(2) - } - result := Result{ - Version: ProtocolVersion, TaskID: invocation.Request.TaskID, Attempt: invocation.Request.Attempt, - Stage: invocation.Request.Stage, Status: StatusPassed, Summary: "from child", - } - switch os.Getenv("AGENT_HELPER_BEHAVIOR") { - case "success": - _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) - case "worker-error": - _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result, Error: "provider unavailable"}) - case "malformed": - if _, err := fmt.Fprint(os.Stdout, "not-json"); err != nil { - os.Exit(2) - } - case "oversized": - if _, err := fmt.Fprint(os.Stdout, strings.Repeat("x", maxProtocolBytes+1)); err != nil { - os.Exit(2) - } - case "multiple": - _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) - _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) - case "mismatched": - result.Attempt++ - _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) - case "exit": - fmt.Fprintln(os.Stderr, "child diagnostic") - os.Exit(2) - case "hang": - time.Sleep(10 * time.Second) - case "spawn-grandchild": - cmd := exec.CommandContext(ctx, "/bin/sh", "-c", `sleep 0.2; printf survived > "$AGENT_HELPER_MARKER"`) - cmd.Env = os.Environ() - if err := cmd.Start(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(2) - } - time.Sleep(10 * time.Second) - case "provider-scope": - if len(invocation.Providers) != 1 || invocation.Providers["provider"].APIKeyEnv != "PROVIDER_KEY" || - os.Getenv("PROVIDER_KEY") != "selected" || os.Getenv("OTHER_KEY") != "" { - os.Exit(2) - } - _ = json.NewEncoder(os.Stdout).Encode(Response{Version: ProtocolVersion, Result: result}) - default: - os.Exit(2) - } - os.Exit(0) -} diff --git a/internal/agentexec/taskevents.go b/internal/agentexec/taskevents.go index 1ecee025b..593d45f32 100644 --- a/internal/agentexec/taskevents.go +++ b/internal/agentexec/taskevents.go @@ -23,8 +23,7 @@ type EventPublisher interface { // in-process *events.Bus the daemon cannot see -- the worker and the daemon // are separate processes connected only by NATS. This is the bridge that // makes those Emit calls (stage progress, outcome, parking) reach the -// daemon's events table and dashboard timeline the same way an in-process, -// daemon-run workflow's Bus already does. +// daemon's events table and dashboard timeline. // // A marshal or publish failure is logged and the loop continues: one missing // event must never abort the ones after it, and event shipping must never diff --git a/internal/agentexec/toolset.go b/internal/agentexec/toolset.go index 8715c69f7..bf0db4319 100644 --- a/internal/agentexec/toolset.go +++ b/internal/agentexec/toolset.go @@ -78,7 +78,7 @@ type ToolSetOptions struct { Approval tools.ApprovalRequester // OnToolCall, when non-nil, is notified once per completed tool call. - // InProcessRunner populates it so a workflow stage can surface tool + // LoopRunner populates it so a workflow stage can surface tool // activity on the task timeline (archie-core-467's task-transcript // counterpart). Nil means no one is listening. OnToolCall ToolCallReporter @@ -94,11 +94,8 @@ type ToolCallReport struct { Failed bool } -// ToolCallReporter receives one ToolCallReport per completed tool call. Only -// a runner that executes in the same process as its tools can populate this -// -- SubprocessRunner and NATSRunner dispatch to a different process and have -// no visibility into individual calls from here. A nil reporter is valid and -// reports nothing. +// ToolCallReporter receives one ToolCallReport per completed tool call. A nil +// reporter is valid and reports nothing. type ToolCallReporter func(ToolCallReport) // toolCallDetailBytes caps the summary ToolCallReport.Detail carries. This diff --git a/internal/agentexec/worker.go b/internal/agentexec/worker.go deleted file mode 100644 index 4b42f702d..000000000 --- a/internal/agentexec/worker.go +++ /dev/null @@ -1,166 +0,0 @@ -package agentexec - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "log/slog" - "strings" -) - -const maxProtocolBytes = 8 << 20 - -// DefaultRunnerFactory creates an InProcessRunner backed by the ai-sdk runtime. -func DefaultRunnerFactory(providers map[string]Provider, log *slog.Logger) Runner { - return NewInProcessRunner(NewRuntime(providers), log) -} - -// ServeOne decodes and executes exactly one invocation. -func ServeOne(ctx context.Context, in io.Reader, out io.Writer, log *slog.Logger) error { - return serveOne(ctx, in, out, func(invocation Invocation) Runner { - return DefaultRunnerFactory(invocation.Providers, log) - }) -} - -func serveOne(ctx context.Context, in io.Reader, out io.Writer, newRunner func(Invocation) Runner) error { - var invocation Invocation - if err := decodeOne(in, &invocation); err != nil { - return fmt.Errorf("decode invocation: %w", err) - } - if err := invocation.Validate(); err != nil { - return err - } - runner := newRunner(invocation) - if runner == nil { - return fmt.Errorf("agent runner is not configured") - } - result, runErr := runner.Run(ctx, invocation.Workspace, invocation.Request, nil) - response := Response{Version: ProtocolVersion, Result: result} - if runErr != nil { - response.Error = runErr.Error() - } - if err := json.NewEncoder(out).Encode(response); err != nil { - return fmt.Errorf("encode response: %w", err) - } - return nil -} - -// ReplyFunc sends a response back to the daemon. -type ReplyFunc func(data []byte) error - -// RunnerFactory creates a Runner from provider config. In production this -// calls NewRuntime + NewInProcessRunner; tests inject a mock. -type RunnerFactory func(Providers map[string]Provider, log *slog.Logger) Runner - -// HandleMessage processes one AgentRequestMessage. When msg.Stages is -// populated and msg.Workflow is set, it runs all stages as a per-task -// batch. Otherwise it falls back to single-stage execution. -// -// It passes a nil ToolCallReporter to every Run call: this path has no -// TaskContext and therefore no events.Bus to report through. The workflow -// engine's own AgentStage.Stage().Run (agent.go) is what wires a real -// reporter into tc.Emit; this entry point predates that and is not reached -// by workflow.Run. -func HandleMessage(ctx context.Context, msg AgentRequestMessage, log *slog.Logger, newRunner RunnerFactory) (*AgentResponseEnvelope, error) { - runner := newRunner(msg.Providers, log) - if runner == nil { - return nil, fmt.Errorf("no providers configured in request") - } - - channel := msg.Channel - if channel == "" { - channel = "response" - } - - // Per-task mode: run all stages for this workflow as a batch. - if msg.Workflow != "" && len(msg.Stages) > 0 { - return runStages(ctx, runner, msg, channel, log) - } - - // Single-stage mode (backward compatible). - result, runErr := runner.Run(ctx, msg.Workspace, msg.Request, nil) - resp := &AgentResponseEnvelope{ - Version: msg.Request.Version, - Result: result, - Channel: channel, - } - if runErr != nil { - resp.Error = runErr.Error() - } - return resp, nil -} - -// runStages executes every stage in msg.Stages sequentially, accumulating -// tokens, iterations, and notes. The first failure stops the batch and -// returns immediately. On success, TaskCompleted is set. -func runStages(ctx context.Context, runner Runner, msg AgentRequestMessage, channel string, log *slog.Logger) (*AgentResponseEnvelope, error) { - var ( - totalTokens int - totalIter int - lastResult Result - combinedNotes []string - combinedDetail []string - ) - - for i, stage := range msg.Stages { - log.Info("running stage", "stage", stage.Stage, "batch", fmt.Sprintf("%d/%d", i+1, len(msg.Stages))) - result, runErr := runner.Run(ctx, msg.Workspace, stage, nil) - if runErr != nil { - resp := &AgentResponseEnvelope{ - Version: stage.Version, - Result: result, - Error: runErr.Error(), - Channel: channel, - } - return resp, nil //nolint:nilerr // runErr is reported to the caller in the response envelope's Error field; returning it here as well would double-report and abort the NATS reply - } - totalTokens += result.TokensUsed - totalIter += result.Iterations - combinedNotes = append(combinedNotes, result.AppendedNotes...) - if result.Summary != "" { - combinedDetail = append(combinedDetail, fmt.Sprintf("[%s] %s", stage.Stage, result.Summary)) - } - lastResult = result - if result.Status != StatusPassed { - break - } - } - - lastResult.TokensUsed = totalTokens - lastResult.Iterations = totalIter - lastResult.AppendedNotes = combinedNotes - if len(combinedDetail) > 0 { - lastResult.Summary = strings.Join(combinedDetail, "\n") - } - - return &AgentResponseEnvelope{ - Version: lastResult.Version, - Result: lastResult, - Channel: channel, - TaskCompleted: lastResult.Status == StatusPassed, - }, nil -} - -func decodeOne(r io.Reader, value any) error { - data, err := io.ReadAll(io.LimitReader(r, maxProtocolBytes+1)) - if err != nil { - return err - } - if len(data) > maxProtocolBytes { - return fmt.Errorf("JSON value exceeds %d bytes", maxProtocolBytes) - } - decoder := json.NewDecoder(bytes.NewReader(data)) - if err := decoder.Decode(value); err != nil { - return err - } - var extra any - if err := decoder.Decode(&extra); err != io.EOF { - if err == nil { - return fmt.Errorf("multiple JSON values are not allowed") - } - return err - } - return nil -} diff --git a/internal/app/agentworker/architecture_test.go b/internal/app/agentworker/architecture_test.go index fb6a091d7..27a78add0 100644 --- a/internal/app/agentworker/architecture_test.go +++ b/internal/app/agentworker/architecture_test.go @@ -49,3 +49,18 @@ func TestApplicationOwnsNoTransportWireMechanics(t *testing.T) { }) } } + +// Full-task request/reply is the worker's only production entry point. A +// single-stage loop would recreate the obsolete split where archied owns the +// workflow and remotely invokes each stage. +func TestApplicationContainsNoSingleStageWorkerLoop(t *testing.T) { + for _, path := range []string{"single_stage_request.go", "stage_loop.go"} { + matches, err := filepath.Glob(path) + if err != nil { + t.Fatal(err) + } + if len(matches) != 0 { + t.Errorf("legacy single-stage worker file still exists: %s", path) + } + } +} diff --git a/internal/app/agentworker/single_stage_request.go b/internal/app/agentworker/single_stage_request.go deleted file mode 100644 index 12f5185f8..000000000 --- a/internal/app/agentworker/single_stage_request.go +++ /dev/null @@ -1,95 +0,0 @@ -package agentworker - -import ( - "context" - "fmt" - "log/slog" - - "github.com/samcharles93/archie-core/internal/agentexec" - "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/tools" -) - -type singleStageRequestDependencies struct { - handleMessage func(context.Context, agentexec.AgentRequestMessage, *slog.Logger, agentexec.RunnerFactory) (*agentexec.AgentResponseEnvelope, error) - startProviders func(context.Context, []config.MCPServer, *slog.Logger) (*mcpProviderSet, error) - newRunner func(map[string]agentexec.Provider, *slog.Logger, ...*tools.Registry) agentexec.Runner -} - -func productionSingleStageDependencies() singleStageRequestDependencies { - return singleStageRequestDependencies{ - handleMessage: agentexec.HandleMessage, - startProviders: startMCPProviders, - newRunner: newSingleStageRunner, - } -} - -func newSingleStageRunner( - providers map[string]agentexec.Provider, - log *slog.Logger, - registries ...*tools.Registry, -) agentexec.Runner { - return agentexec.NewInProcessRunner(agentexec.NewRuntime(providers), log, registries...) -} - -func handleSingleStageRequest( - ctx context.Context, - message agentexec.StageMessage, - log *slog.Logger, - dependencies singleStageRequestDependencies, -) error { - request, err := message.Request() - if err != nil { - return err - } - - attributes := []any{ - "task", request.TaskID, - "attempt", request.Attempt, - "stage", request.Stage, - "workflow", request.Workflow, - } - attributes = append(attributes, message.LogAttributes()...) - log.Info("processing stage", attributes...) - - startProviders := dependencies.startProviders - if startProviders == nil { - startProviders = startMCPProviders - } - newRunner := dependencies.newRunner - if newRunner == nil { - newRunner = newSingleStageRunner - } - - mcpSet, mcpErr := startProviders(ctx, request.MCPServers, log) - if mcpSet != nil { - defer mcpSet.cleanup(ctx, log) - } - if mcpErr != nil { - log.Warn("mcp providers had errors, continuing with available tools", "err", mcpErr) - } - - factory := func(providers map[string]agentexec.Provider, log *slog.Logger) agentexec.Runner { - var registries []*tools.Registry - if mcpSet != nil { - registries = append(registries, mcpSet.registry) - } - return newRunner(providers, log, registries...) - } - - response, err := dependencies.handleMessage(ctx, request, log, factory) - if err != nil { - return fmt.Errorf("handle: %w", err) - } - if err := message.Respond(ctx, response); err != nil { - return err - } - - log.Info( - "stage complete", - "task", request.TaskID, - "stage", request.Stage, - "status", response.Result.Status, - ) - return nil -} diff --git a/internal/app/agentworker/single_stage_request_test.go b/internal/app/agentworker/single_stage_request_test.go deleted file mode 100644 index 49e668f6f..000000000 --- a/internal/app/agentworker/single_stage_request_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package agentworker - -import ( - "bytes" - "context" - "errors" - "log/slog" - "strings" - "testing" - - "github.com/samcharles93/archie-core/internal/agentexec" - "github.com/samcharles93/archie-core/internal/config" - "github.com/samcharles93/archie-core/internal/tools" - toolprovider "github.com/samcharles93/archie-core/internal/tools/provider" -) - -func singleStageLogger() (*slog.Logger, *bytes.Buffer) { - var output bytes.Buffer - return slog.New(slog.NewTextHandler(&output, nil)), &output -} - -func TestHandleSingleStageRequestReturnsTypedBoundaryAndExecutionFailures(t *testing.T) { - requestErr := errors.New("decode request: invalid") - handleErr := errors.New("agent execution failed") - respondErr := errors.New("publish response: unavailable") - tests := []struct { - name string - message *stageMessageStub - handleErr error - wantErr error - wantHandle int - wantReply int - }{ - {name: "typed boundary", message: &stageMessageStub{requestErr: requestErr}, wantErr: requestErr}, - {name: "execution", message: &stageMessageStub{request: agentexec.AgentRequestMessage{TaskID: 17}}, handleErr: handleErr, wantErr: handleErr, wantHandle: 1}, - {name: "response", message: &stageMessageStub{request: agentexec.AgentRequestMessage{TaskID: 23}, respondErr: respondErr}, wantErr: respondErr, wantHandle: 1, wantReply: 1}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - handleCalls := 0 - dependencies := singleStageRequestDependencies{ - handleMessage: func(context.Context, agentexec.AgentRequestMessage, *slog.Logger, agentexec.RunnerFactory) (*agentexec.AgentResponseEnvelope, error) { - handleCalls++ - return &agentexec.AgentResponseEnvelope{Result: agentexec.Result{Status: agentexec.StatusPassed}}, test.handleErr - }, - } - err := handleSingleStageRequest(t.Context(), test.message, slog.New(slog.DiscardHandler), dependencies) - if !errors.Is(err, test.wantErr) { - t.Fatalf("error = %v, want %v", err, test.wantErr) - } - if handleCalls != test.wantHandle || test.message.respondCalls != test.wantReply { - t.Fatalf("handle/respond calls = (%d,%d), want (%d,%d)", handleCalls, test.message.respondCalls, test.wantHandle, test.wantReply) - } - }) - } -} - -func TestHandleSingleStageRequestAttachesAndCleansUpMCPProviders(t *testing.T) { - message := &stageMessageStub{request: agentexec.AgentRequestMessage{ - TaskID: 29, - Stage: "implement", - MCPServers: []config.MCPServer{{Name: "available"}}, - }} - registry := tools.NewRegistry() - if err := registry.Register(testTool("available")); err != nil { - t.Fatal(err) - } - provider := &fakeMCPEngine{id: "available"} - set := &mcpProviderSet{providers: []toolprovider.Engine{provider}, registry: registry} - startCalls := 0 - factoryCalls := 0 - dependencies := singleStageRequestDependencies{ - startProviders: func(_ context.Context, servers []config.MCPServer, _ *slog.Logger) (*mcpProviderSet, error) { - startCalls++ - if len(servers) != 1 || servers[0].Name != "available" { - t.Fatalf("MCP servers = %#v", servers) - } - return set, nil - }, - newRunner: func(_ map[string]agentexec.Provider, _ *slog.Logger, registries ...*tools.Registry) agentexec.Runner { - factoryCalls++ - if len(registries) != 1 || registries[0] != registry { - t.Fatalf("runner registries = %#v", registries) - } - return panicRunner{t: t} - }, - handleMessage: func(_ context.Context, request agentexec.AgentRequestMessage, _ *slog.Logger, factory agentexec.RunnerFactory) (*agentexec.AgentResponseEnvelope, error) { - if runner := factory(request.Providers, slog.New(slog.DiscardHandler)); runner == nil { - t.Fatal("runner factory returned nil") - } - return &agentexec.AgentResponseEnvelope{Result: agentexec.Result{Status: agentexec.StatusPassed}}, nil - }, - } - if err := handleSingleStageRequest(t.Context(), message, slog.New(slog.DiscardHandler), dependencies); err != nil { - t.Fatal(err) - } - if startCalls != 1 || factoryCalls != 1 || provider.stops != 1 || message.respondCalls != 1 { - t.Fatalf("start/factory/stops/respond = (%d,%d,%d,%d), want all 1", startCalls, factoryCalls, provider.stops, message.respondCalls) - } -} - -func TestHandleSingleStageRequestPreservesLifecycleLogs(t *testing.T) { - message := &stageMessageStub{request: agentexec.AgentRequestMessage{ - TaskID: 31, Attempt: 4, Stage: "test", Workflow: "tdd", - MCPServers: []config.MCPServer{{Name: "broken", Transport: "stdio"}}, - }} - dependencies := productionSingleStageDependencies() - dependencies.handleMessage = func(context.Context, agentexec.AgentRequestMessage, *slog.Logger, agentexec.RunnerFactory) (*agentexec.AgentResponseEnvelope, error) { - return &agentexec.AgentResponseEnvelope{Result: agentexec.Result{Status: agentexec.StatusPassed}}, nil - } - log, output := singleStageLogger() - if err := handleSingleStageRequest(t.Context(), message, log, dependencies); err != nil { - t.Fatal(err) - } - for _, expected := range []string{ - "processing stage", "task=31", "attempt=4", "stage=test", "workflow=tdd", "reply_to=_INBOX.test", - "mcp providers had errors, continuing with available tools", "stage complete", "status=passed", - } { - if !strings.Contains(output.String(), expected) { - t.Fatalf("log output %q does not contain %q", output.String(), expected) - } - } -} diff --git a/internal/app/agentworker/stage_loop.go b/internal/app/agentworker/stage_loop.go deleted file mode 100644 index 489408927..000000000 --- a/internal/app/agentworker/stage_loop.go +++ /dev/null @@ -1,57 +0,0 @@ -package agentworker - -import ( - "context" - "errors" - "log/slog" - "time" - - "github.com/samcharles93/archie-core/internal/agentexec" - "github.com/samcharles93/archie-core/internal/eventbus" -) - -// stageBus is the typed single-stage delivery capability required by the loop. -type stageBus interface { - agentexec.StageConsumer -} - -// runMainLoop runs the fetch-handle-ack loop until the context is cancelled. -func runMainLoop(ctx context.Context, bus stageBus, log *slog.Logger) int { - return runMainLoopWithDelay(ctx, bus, log, time.Sleep) -} - -func runMainLoopWithDelay(ctx context.Context, bus stageBus, log *slog.Logger, delay func(time.Duration)) int { - for { - if ctx.Err() != nil { - log.Info("archie-agent shutting down") - return 0 - } - message, err := bus.FetchStage(ctx) - switch { - case errors.Is(err, eventbus.ErrNoMessage): - continue - case err != nil: - if ctx.Err() != nil { - return 0 - } - log.Error("fetch failed", "err", err) - delay(time.Second) - continue - } - if err := handleSingleStageRequest(ctx, message, log, productionSingleStageDependencies()); err != nil { - log.Error("handle failed", "err", err) - if err := message.Nak(); err != nil { - log.Warn("nak failed", "err", err) - } - // A Nak requests redelivery. Without a backoff, a deterministic - // failure (a broken gate, a malformed request) refetches and - // fails again immediately, flooding the log with one line per - // loop iteration instead of one per genuine retry. - delay(time.Second) - continue - } - if err := message.Ack(); err != nil { - log.Warn("ack failed", "err", err) - } - } -} diff --git a/internal/app/agentworker/stage_loop_test.go b/internal/app/agentworker/stage_loop_test.go deleted file mode 100644 index cdba81124..000000000 --- a/internal/app/agentworker/stage_loop_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package agentworker - -import ( - "bytes" - "context" - "errors" - "log/slog" - "strings" - "testing" - "time" - - "github.com/samcharles93/archie-core/internal/agentexec" - "github.com/samcharles93/archie-core/internal/eventbus" -) - -type stageFetch struct { - message agentexec.StageMessage - err error - before func() -} - -type stageBusStub struct { - fetches []stageFetch - fetchCalls int -} - -func (b *stageBusStub) FetchStage(context.Context) (agentexec.StageMessage, error) { - if b.fetchCalls >= len(b.fetches) { - panic("unexpected FetchStage call") - } - fetch := b.fetches[b.fetchCalls] - b.fetchCalls++ - if fetch.before != nil { - fetch.before() - } - return fetch.message, fetch.err -} - -type stageMessageStub struct { - request agentexec.AgentRequestMessage - requestErr error - respondErr error - ackErr error - nakErr error - respondCancel context.CancelFunc - respondCalls int - ackCalls int - nakCalls int -} - -func (m *stageMessageStub) Request() (agentexec.AgentRequestMessage, error) { - return m.request, m.requestErr -} - -func (m *stageMessageStub) Respond(context.Context, *agentexec.AgentResponseEnvelope) error { - m.respondCalls++ - if m.respondCancel != nil { - m.respondCancel() - } - return m.respondErr -} - -func (m *stageMessageStub) Ack() error { m.ackCalls++; return m.ackErr } -func (m *stageMessageStub) Nak() error { m.nakCalls++; return m.nakErr } -func (*stageMessageStub) LogAttributes() []any { return []any{"reply_to", "_INBOX.test"} } - -func stageLoopLogger() (*slog.Logger, *bytes.Buffer) { - var output bytes.Buffer - return slog.New(slog.NewTextHandler(&output, nil)), &output -} - -func noDelay(t *testing.T) (func(time.Duration), *[]time.Duration) { - t.Helper() - var calls []time.Duration - return func(duration time.Duration) { calls = append(calls, duration) }, &calls -} - -func TestRunMainLoopExitsImmediatelyWhenAlreadyCancelled(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - cancel() - bus := &stageBusStub{} - log, output := stageLoopLogger() - if code := runMainLoop(ctx, bus, log); code != 0 { - t.Fatalf("runMainLoop() = %d, want 0", code) - } - if bus.fetchCalls != 0 || !strings.Contains(output.String(), "archie-agent shutting down") { - t.Fatalf("fetches/log = (%d, %q), want no fetch and shutdown log", bus.fetchCalls, output.String()) - } -} - -func TestRunMainLoopFetchOutcomes(t *testing.T) { - fetchErr := errors.New("temporary fetch failure") - tests := []struct { - name string - firstErr error - wantDelay bool - wantLog bool - }{ - {name: "idle", firstErr: eventbus.ErrNoMessage}, - {name: "failure", firstErr: fetchErr, wantDelay: true, wantLog: true}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - bus := &stageBusStub{fetches: []stageFetch{ - {err: test.firstErr}, - {err: errors.New("fetch after cancellation"), before: cancel}, - }} - log, output := stageLoopLogger() - delay, delays := noDelay(t) - if code := runMainLoopWithDelay(ctx, bus, log, delay); code != 0 { - t.Fatalf("runMainLoopWithDelay() = %d, want 0", code) - } - if got := len(*delays) == 1 && (*delays)[0] == time.Second; got != test.wantDelay { - t.Fatalf("delayed = %v (%v), want %v", got, *delays, test.wantDelay) - } - if got := strings.Contains(output.String(), "fetch failed"); got != test.wantLog { - t.Fatalf("fetch failure logged = %v, want %v; %q", got, test.wantLog, output.String()) - } - }) - } -} - -func TestRunMainLoopStopsWhenFetchCancelsContext(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - bus := &stageBusStub{fetches: []stageFetch{{err: errors.New("interrupted"), before: cancel}}} - log, output := stageLoopLogger() - delay, delays := noDelay(t) - if code := runMainLoopWithDelay(ctx, bus, log, delay); code != 0 { - t.Fatalf("runMainLoopWithDelay() = %d, want 0", code) - } - if len(*delays) != 0 || output.Len() != 0 { - t.Fatalf("delay/log = (%v, %q), want none", *delays, output.String()) - } -} - -func TestRunMainLoopNaksHandleErrorsAndContinues(t *testing.T) { - for _, test := range []struct { - name string - nakErr error - wantNakLog bool - }{ - {name: "nak succeeds"}, - {name: "nak fails", nakErr: errors.New("nak unavailable"), wantNakLog: true}, - } { - t.Run(test.name, func(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - message := &stageMessageStub{requestErr: errors.New("decode request: invalid"), nakErr: test.nakErr} - bus := &stageBusStub{fetches: []stageFetch{{message: message}, {err: errors.New("cancelled"), before: cancel}}} - log, output := stageLoopLogger() - delay, delays := noDelay(t) - runMainLoopWithDelay(ctx, bus, log, delay) - if message.nakCalls != 1 || message.ackCalls != 0 { - t.Fatalf("nak/ack = (%d,%d), want (1,0)", message.nakCalls, message.ackCalls) - } - if got := strings.Contains(output.String(), "nak failed"); got != test.wantNakLog { - t.Fatalf("nak failure logged = %v, want %v", got, test.wantNakLog) - } - // A Nak requests redelivery, so without a backoff the very next - // FetchStage hands back the same failing message immediately -- - // a deterministic failure (e.g. a broken gate) then spins as a - // tight log-flooding loop instead of backing off. - if len(*delays) != 1 || (*delays)[0] != time.Second { - t.Fatalf("delays = %v, want a single %v backoff before refetching a nak'd message", *delays, time.Second) - } - }) - } -} - -func TestRunMainLoopAcksSuccessfulHandleAndContinues(t *testing.T) { - for _, test := range []struct { - name string - ackErr error - wantAckLog bool - }{ - {name: "ack succeeds"}, - {name: "ack fails", ackErr: errors.New("ack unavailable"), wantAckLog: true}, - } { - t.Run(test.name, func(t *testing.T) { - ctx, cancel := context.WithCancel(t.Context()) - message := &stageMessageStub{ - request: agentexec.AgentRequestMessage{Providers: map[string]agentexec.Provider{"test": {Class: "openai"}}}, - ackErr: test.ackErr, - respondCancel: cancel, - } - bus := &stageBusStub{fetches: []stageFetch{{message: message}}} - log, output := stageLoopLogger() - delay, _ := noDelay(t) - runMainLoopWithDelay(ctx, bus, log, delay) - if message.respondCalls != 1 || message.ackCalls != 1 || message.nakCalls != 0 { - t.Fatalf("respond/ack/nak = (%d,%d,%d), want (1,1,0)", message.respondCalls, message.ackCalls, message.nakCalls) - } - if got := strings.Contains(output.String(), "ack failed"); got != test.wantAckLog { - t.Fatalf("ack failure logged = %v, want %v", got, test.wantAckLog) - } - }) - } -} diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index b34542519..a285dd932 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -118,10 +118,16 @@ type taskDependencies struct { events agentexec.EventPublisher } +type runnerFactory func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner + +func newTaskRunner(providers map[string]agentexec.Provider, log *slog.Logger) agentexec.Runner { + return agentexec.NewLoopRunner(agentexec.NewRuntime(providers), log) +} + // runTask builds a workflow.Registry from the container's mounted worktree, // routes and runs the entire workflow, and reports its terminal outcome. // Store remains archied's authority; Response.Task is a logging snapshot. -func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependencies, newRunner agentexec.RunnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) { +func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependencies, newRunner runnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) { registry, err := skillbuild.BuildRegistry(workDir) if err != nil { return nil, fmt.Errorf("build registry: %w", err) @@ -150,7 +156,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen // Build a runner with MCP-discovered tools when available. var agent agentexec.Runner if mcpSet != nil && mcpSet.registry != nil { - agent = agentexec.NewInProcessRunner(agentexec.NewRuntime(req.Providers), log, mcpSet.registry) + agent = agentexec.NewLoopRunner(agentexec.NewRuntime(req.Providers), log, mcpSet.registry) } else { agent = newRunner(req.Providers, log) } diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 43a09f413..56bf82e06 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -319,7 +319,7 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { t.Fatalf("prepare: %v", err) } req := taskrun.Request{Task: task, Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, Cfg: config.Config{}.ForTask()} - fakeRunner := agentexec.RunnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return panicRunner{t} }) + fakeRunner := runnerFactory(func(map[string]agentexec.Provider, *slog.Logger) agentexec.Runner { return panicRunner{t} }) response, err := runTask(ctx, req, taskDependencies{forge: fg, store: st, trees: remote}, fakeRunner, hostDir, slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("runTask: %v", err) @@ -392,10 +392,7 @@ func TestExecuteTaskRequestUsesInfrastructureRPCDependencies(t *testing.T) { } t.Cleanup(unsubTrees) - transport, err := agentnats.Connect(ctx, agentnats.Config{ - URL: srv.ClientURL(), - ConsumerName: "rpc-bootstrap-test", - }, slog.New(slog.DiscardHandler)) + transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL()}, slog.New(slog.DiscardHandler)) if err != nil { t.Fatal(err) } @@ -518,10 +515,7 @@ func TestExecuteTaskRequestForwardsWorkflowEventsOverNATS(t *testing.T) { t.Fatal(err) } - transport, err := agentnats.Connect(ctx, agentnats.Config{ - URL: srv.ClientURL(), - ConsumerName: "rpc-events-test", - }, slog.New(slog.DiscardHandler)) + transport, err := agentnats.Connect(ctx, agentnats.Config{URL: srv.ClientURL()}, slog.New(slog.DiscardHandler)) if err != nil { t.Fatal(err) } diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index 116e9f7ad..991f22ebb 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -3,7 +3,6 @@ package agentworker import ( "context" - "errors" "log/slog" "time" @@ -33,16 +32,14 @@ func (e *StartupError) Unwrap() error { return e.Err } type Settings struct { NATSURL string NATSToken string - Consumer string WorkDir string } type workerTransport interface { - agentexec.StageConsumer Close() LogPublisher() agentexec.LogPublisher EventPublisher() agentexec.EventPublisher - SubscribeTasks(context.Context, int64, bool, agentnats.TaskHandler, *slog.Logger) (agentnats.Subscription, error) + SubscribeTasks(context.Context, int64, agentnats.TaskHandler, *slog.Logger) (agentnats.Subscription, error) Forger(string, time.Duration) workflow.Forger Store(time.Duration) store.WorkflowStore Trees(string, string, time.Duration) agentnats.RemoteTrees @@ -51,8 +48,8 @@ type workerTransport interface { type workerDependencies struct { connect func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error) markSafe func(context.Context, string, *slog.Logger) bool - bootID func(string) (int64, bool, error) - runLoop func(context.Context, stageBus, *slog.Logger) int + bootID func(string) (int64, error) + wait func(context.Context, *slog.Logger) } func productionWorkerDependencies() workerDependencies { @@ -62,12 +59,15 @@ func productionWorkerDependencies() workerDependencies { }, markSafe: agentgit.MarkSafe, bootID: agentboot.TaskID, - runLoop: runMainLoop, + wait: func(ctx context.Context, log *slog.Logger) { + <-ctx.Done() + log.Info("archie-agent shutting down") + }, } } -// Run starts the worker, serves full-task and single-stage requests, and -// returns after ctx cancellation or a startup failure. +// Run starts the worker, serves full-task requests, and returns after ctx +// cancellation or a startup failure. func Run(ctx context.Context, settings Settings, log *slog.Logger) error { return run(ctx, settings, log, productionWorkerDependencies()) } @@ -84,31 +84,25 @@ func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies dependencies.markSafe(ctx, workDir, log) transport, err := dependencies.connect(ctx, agentnats.Config{ - URL: settings.NATSURL, - Token: settings.NATSToken, - ConsumerName: settings.Consumer, + URL: settings.NATSURL, + Token: settings.NATSToken, }, log) if err != nil { operation := "nats connect failed" - if errors.Is(err, agentnats.ErrCoreConnectionUnavailable) { - operation = "nats connection unavailable" - } log.Error(operation, "err", err) return &StartupError{Operation: operation, Err: err} } defer transport.Close() - taskID, dedicated, err := dependencies.bootID(workDir) + taskID, err := dependencies.bootID(workDir) if err != nil { log.Error("task boot failed", "err", err) return &StartupError{Operation: "task boot failed", Err: err} } - if dedicated { - log = slog.New(agentexec.NewSystemLogHandler(log.Handler(), transport.LogPublisher(), taskID)) - log.Info("system log publisher attached", "task", taskID) - } + log = slog.New(agentexec.NewSystemLogHandler(log.Handler(), transport.LogPublisher(), taskID)) + log.Info("system log publisher attached", "task", taskID) - subscription, err := transport.SubscribeTasks(ctx, taskID, dedicated, func(ctx context.Context, request taskrun.Request) (*taskrun.Response, error) { + subscription, err := transport.SubscribeTasks(ctx, taskID, func(ctx context.Context, request taskrun.Request) (*taskrun.Response, error) { return executeTaskRequest(ctx, request, transport, workDir, log) }, log) if err != nil { @@ -121,8 +115,8 @@ func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies } }() - log.Info("archie-agent ready", "nats", settings.NATSURL, "consumer", settings.Consumer) - dependencies.runLoop(ctx, transport, log) + log.Info("archie-agent ready", "nats", settings.NATSURL) + dependencies.wait(ctx, log) return nil } @@ -141,7 +135,7 @@ func executeTaskRequest(ctx context.Context, request taskrun.Request, transport trees: transport.Trees(request.Task.Identity, request.WorktreeGrant, rpcTimeout), events: transport.EventPublisher(), } - response, err := runTask(ctx, request, dependencies, agentexec.DefaultRunnerFactory, workDir, log) + response, err := runTask(ctx, request, dependencies, newTaskRunner, workDir, log) if err != nil { log.Error("task run failed", "task", request.Task.ID, "err", err) return nil, err diff --git a/internal/app/agentworker/worker_test.go b/internal/app/agentworker/worker_test.go index c7e0dc746..39c0ba904 100644 --- a/internal/app/agentworker/worker_test.go +++ b/internal/app/agentworker/worker_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "errors" - "fmt" "log/slog" "strings" "testing" @@ -41,12 +40,9 @@ type workerTransportStub struct { subCloseErr error publisher agentexec.LogPublisher eventPublisher agentexec.EventPublisher - dedicated bool + taskID int64 } -func (*workerTransportStub) FetchStage(context.Context) (agentexec.StageMessage, error) { - return nil, nil -} func (t *workerTransportStub) Close() { *t.events = append(*t.events, "transport-close") } func (t *workerTransportStub) LogPublisher() agentexec.LogPublisher { *t.events = append(*t.events, "log-publisher") @@ -64,9 +60,9 @@ func (t *workerTransportStub) EventPublisher() agentexec.EventPublisher { return workerPublisher{} } -func (t *workerTransportStub) SubscribeTasks(_ context.Context, _ int64, dedicated bool, _ agentnats.TaskHandler, _ *slog.Logger) (agentnats.Subscription, error) { +func (t *workerTransportStub) SubscribeTasks(_ context.Context, taskID int64, _ agentnats.TaskHandler, _ *slog.Logger) (agentnats.Subscription, error) { *t.events = append(*t.events, "subscribe") - t.dedicated = dedicated + t.taskID = taskID if t.subscribeErr != nil { return nil, t.subscribeErr } @@ -93,15 +89,15 @@ func TestRunPassesCompleteTransportConfiguration(t *testing.T) { got = config return transport, nil }, - bootID: func(string) (int64, bool, error) { return 0, false, nil }, - runLoop: func(context.Context, stageBus, *slog.Logger) int { cancel(); return 0 }, + bootID: func(string) (int64, error) { return 42, nil }, + wait: func(context.Context, *slog.Logger) { cancel() }, } - settings := Settings{NATSURL: "nats://test", NATSToken: "secret", Consumer: "worker", WorkDir: "/worktree"} + settings := Settings{NATSURL: "nats://test", NATSToken: "secret", WorkDir: "/worktree"} if err := run(ctx, settings, slog.New(slog.DiscardHandler), dependencies); err != nil { t.Fatal(err) } - if got.URL != settings.NATSURL || got.Token != settings.NATSToken || got.ConsumerName != settings.Consumer { - t.Fatalf("connection config = %#v, want URL/token/consumer from settings", got) + if got.URL != settings.NATSURL || got.Token != settings.NATSToken { + t.Fatalf("connection config = %#v, want URL/token from settings", got) } } @@ -117,19 +113,18 @@ func TestRunPreservesStartupAndReverseCleanupOrder(t *testing.T) { events = append(events, "connect") return transport, nil }, - bootID: func(string) (int64, bool, error) { + bootID: func(string) (int64, error) { events = append(events, "boot-id") - return 42, true, nil + return 42, nil }, - runLoop: func(context.Context, stageBus, *slog.Logger) int { - events = append(events, "stage-loop") - return 0 + wait: func(context.Context, *slog.Logger) { + events = append(events, "wait") }, } - if err := run(t.Context(), Settings{NATSURL: "nats://test", Consumer: "worker", WorkDir: "/worktree"}, slog.New(slog.DiscardHandler), dependencies); err != nil { + if err := run(t.Context(), Settings{NATSURL: "nats://test", WorkDir: "/worktree"}, slog.New(slog.DiscardHandler), dependencies); err != nil { t.Fatal(err) } - want := []string{"git-safety", "connect", "boot-id", "log-publisher", "subscribe", "stage-loop", "subscription-close", "transport-close"} + want := []string{"git-safety", "connect", "boot-id", "log-publisher", "subscribe", "wait", "subscription-close", "transport-close"} if len(events) != len(want) { t.Fatalf("events = %v, want %v", events, want) } @@ -138,8 +133,8 @@ func TestRunPreservesStartupAndReverseCleanupOrder(t *testing.T) { t.Fatalf("events = %v, want %v", events, want) } } - if !transport.dedicated { - t.Fatal("dedicated boot ID did not select dedicated subscription") + if transport.taskID != 42 { + t.Fatalf("subscription task ID = %d, want 42", transport.taskID) } } @@ -152,11 +147,11 @@ func TestRunWarnsWhenNormalSubscriptionCleanupFails(t *testing.T) { connect: func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error) { return transport, nil }, - bootID: func(string) (int64, bool, error) { return 0, false, nil }, - runLoop: func(context.Context, stageBus, *slog.Logger) int { return 0 }, + bootID: func(string) (int64, error) { return 42, nil }, + wait: func(context.Context, *slog.Logger) {}, } var output bytes.Buffer - if err := run(t.Context(), Settings{NATSURL: "nats://test", Consumer: "worker"}, slog.New(slog.NewTextHandler(&output, nil)), dependencies); err != nil { + if err := run(t.Context(), Settings{NATSURL: "nats://test"}, slog.New(slog.NewTextHandler(&output, nil)), dependencies); err != nil { t.Fatal(err) } if !strings.Contains(output.String(), "task run unsubscribe failed") || !strings.Contains(output.String(), closeErr.Error()) { @@ -173,15 +168,13 @@ func TestRunStartupFailuresCleanUpOwnedResources(t *testing.T) { connectErr error bootErr error subscribeErr error - dedicated bool wantErr error wantOperation string wantClosed bool }{ {name: "connect", connectErr: connectErr, wantErr: connectErr, wantOperation: "nats connect failed"}, - {name: "core connection", connectErr: fmt.Errorf("%w: unavailable", agentnats.ErrCoreConnectionUnavailable), wantErr: agentnats.ErrCoreConnectionUnavailable, wantOperation: "nats connection unavailable"}, {name: "boot metadata", bootErr: bootErr, wantErr: bootErr, wantOperation: "task boot failed", wantClosed: true}, - {name: "subscribe", subscribeErr: subscribeErr, dedicated: true, wantErr: subscribeErr, wantOperation: "taskrun subscribe failed", wantClosed: true}, + {name: "subscribe", subscribeErr: subscribeErr, wantErr: subscribeErr, wantOperation: "taskrun subscribe failed", wantClosed: true}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -193,19 +186,16 @@ func TestRunStartupFailuresCleanUpOwnedResources(t *testing.T) { connect: func(context.Context, agentnats.Config, *slog.Logger) (workerTransport, error) { return transport, test.connectErr }, - bootID: func(string) (int64, bool, error) { + bootID: func(string) (int64, error) { if test.bootErr != nil { - return 0, false, test.bootErr + return 0, test.bootErr } - if test.dedicated { - return 42, true, nil - } - return 0, false, nil + return 42, nil }, - runLoop: func(context.Context, stageBus, *slog.Logger) int { t.Fatal("stage loop called"); return 0 }, + wait: func(context.Context, *slog.Logger) { t.Fatal("wait called") }, } var output bytes.Buffer - err := run(t.Context(), Settings{NATSURL: "nats://test", Consumer: "worker"}, slog.New(slog.NewTextHandler(&output, nil)), dependencies) + err := run(t.Context(), Settings{NATSURL: "nats://test"}, slog.New(slog.NewTextHandler(&output, nil)), dependencies) if !errors.Is(err, test.wantErr) { t.Fatalf("error = %v, want %v", err, test.wantErr) } diff --git a/internal/config/clone_test.go b/internal/config/clone_test.go index e53148bee..cef6b680e 100644 --- a/internal/config/clone_test.go +++ b/internal/config/clone_test.go @@ -20,10 +20,10 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { MCPServers: []MCPServer{{Headers: map[string]string{"A": "b"}, Args: []string{"x"}}}, WebFetch: WebFetchConfig{Enabled: &enabled}, }, - Memory: MemoryConfig{ProviderConfig: map[string]string{"k": "v"}}, - Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}}, - Agent: Agent{Env: []string{"HOME"}}, - Extra: map[string]any{"custom": 1}, + Memory: MemoryConfig{ProviderConfig: map[string]string{"k": "v"}}, + Chat: ChatConfig{Telegram: TelegramConfig{AllowedUserIDs: []int64{1}}}, + LegacyAgent: LegacyAgent{Env: []string{"HOME"}}, + Extra: map[string]any{"custom": 1}, } got := orig.Clone() @@ -37,7 +37,7 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { got.Tools.MCPServers[0].Args[0] = "changed" got.Memory.ProviderConfig["k"] = "changed" got.Chat.Telegram.AllowedUserIDs[0] = 99 - got.Agent.Env[0] = "changed" + got.LegacyAgent.Env[0] = "changed" got.Extra["custom"] = 2 *got.Tools.WebFetch.Enabled = false @@ -62,7 +62,7 @@ func TestConfigCloneDeepCopiesReferenceFields(t *testing.T) { if orig.Chat.Telegram.AllowedUserIDs[0] != 1 { t.Error("Telegram.AllowedUserIDs is shared") } - if orig.Agent.Env[0] != "HOME" { + if orig.LegacyAgent.Env[0] != "HOME" { t.Error("Agent.Env is shared") } if orig.Extra["custom"] != 1 { diff --git a/internal/config/config.go b/internal/config/config.go index 9252af58c..8aa77aa27 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -176,15 +176,14 @@ type Provider struct { BaseURL string `toml:"base_url" yaml:"base_url" json:"base_url"` } -// Agent configures how archied executes autonomous stages. -type Agent struct { - // Mode is "inprocess" during migration or "subprocess" to invoke the - // standalone archie-agent worker for every autonomous stage. - Mode string `toml:"mode" yaml:"mode"` - // Command is the archie-agent executable path used in subprocess mode. - Command string `toml:"command" yaml:"command"` - // Env adds environment variable names to the worker allowlist. - Env []string `toml:"env" yaml:"env"` +// LegacyAgent decodes the removed [agent] section so existing operator files +// continue to load during migration. Its fields have no runtime consumers: +// autonomous work always uses a task-scoped archie-agent container over NATS. +// Remove the section from new and updated configurations. +type LegacyAgent struct { + Mode string `toml:"mode" yaml:"mode"` + Command string `toml:"command" yaml:"command"` + Env []string `toml:"env" yaml:"env"` } // Forge intake modes for Forge.Intake. Poll is the default; webhook reacts to @@ -414,8 +413,8 @@ type Config struct { // model ref ("provider/model"). Models map[string]string `toml:"models" yaml:"models"` - Providers map[string]Provider `toml:"providers" yaml:"providers"` - Agent Agent `toml:"agent" yaml:"agent"` + Providers map[string]Provider `toml:"providers" yaml:"providers"` + LegacyAgent LegacyAgent `toml:"agent" yaml:"agent"` Budgets Budgets `toml:"budgets" yaml:"budgets"` Web Web `toml:"web" yaml:"web"` @@ -540,7 +539,7 @@ func (c Config) Clone() Config { c.Models = cloneStringMap(c.Models) c.Providers = maps.Clone(c.Providers) c.Dispatch.Labels = cloneStringMap(c.Dispatch.Labels) - c.Agent.Env = append([]string(nil), c.Agent.Env...) + c.LegacyAgent.Env = append([]string(nil), c.LegacyAgent.Env...) c.Repos = cloneRepos(c.Repos) c.Identities = cloneIdentities(c.Identities) c.Chat.Models = append([]string(nil), c.Chat.Models...) @@ -669,7 +668,7 @@ type CaptureConfig struct { // ContainerConfig configures Docker sandbox execution of archie-agent. type ContainerConfig struct { - // Enabled activates container execution. Requires agent.mode = "nats". + // Enabled activates autonomous workflow execution in managed containers. Enabled bool `toml:"enabled" yaml:"enabled"` // Image is the Docker image to run (e.g. "ghcr.io/sam/archie-agent:latest"). Image string `toml:"image" yaml:"image"` diff --git a/internal/container/pool.go b/internal/container/pool.go index ea6a73bd5..cd7d95e14 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -1,7 +1,7 @@ // Package container manages Docker containers running archie-agent. // A Pool acquires and releases containers per task, handling image pull, -// creation, startup, health check, and teardown. The daemon's existing -// NATSRunner handles agent communication unchanged. +// creation, startup, health check, and teardown. The daemon hands each task to +// its container as one core-NATS request. package container import ( diff --git a/internal/daemon/architecture_test.go b/internal/daemon/architecture_test.go index e11086c8c..ce8adcf51 100644 --- a/internal/daemon/architecture_test.go +++ b/internal/daemon/architecture_test.go @@ -74,3 +74,37 @@ func reportLocalWorkflowRun(t *testing.T, fileset *token.FileSet, call *ast.Call position := fileset.Position(call.Pos()) t.Errorf("%s calls workflow.Run; autonomous workflows must use the full-task worker handoff", position) } + +// Daemon and IdentityRunner carry routing and authority state only. Keeping a +// stage runner or workflow registry on either type makes a host execution path +// one call away from returning. +func TestDaemonCarriesNoLocalWorkflowExecutionState(t *testing.T) { + file, err := parser.ParseFile(token.NewFileSet(), "daemon.go", nil, 0) + if err != nil { + t.Fatal(err) + } + forbidden := map[string]bool{"Agent": true, "Workflows": true, "CustomStages": true} + for _, declaration := range file.Decls { + gen, ok := declaration.(*ast.GenDecl) + if !ok { + continue + } + for _, spec := range gen.Specs { + typeSpec, ok := spec.(*ast.TypeSpec) + if !ok || (typeSpec.Name.Name != "Daemon" && typeSpec.Name.Name != "IdentityRunner") { + continue + } + structure, ok := typeSpec.Type.(*ast.StructType) + if !ok { + continue + } + for _, field := range structure.Fields.List { + for _, name := range field.Names { + if forbidden[name.Name] { + t.Errorf("%s carries local workflow execution field %s", typeSpec.Name.Name, name.Name) + } + } + } + } + } +} diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index d0d7690f7..1318a641c 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -18,7 +18,6 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/domain/curator" - "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/eventbus" "github.com/samcharles93/archie-core/internal/events" @@ -72,9 +71,7 @@ type Daemon struct { Store store.TaskStore Forge forge.Forge Trees *worktree.Manager - Agent agentexec.Runner Bus *events.Bus - Workflows workflow.Registry Log *slog.Logger // Tasks is the optional message bus for task distribution. Nil means no // bus is configured; the existing SQLite ClaimNext flow is used. @@ -83,7 +80,7 @@ type Daemon struct { // TaskRunReadyTimeout bounds how long runViaAgent retries an initial // taskrun request that fails with nats.ErrNoResponders, giving a // freshly spawned archie-agent container time to connect to NATS, set - // up its JetStream stream/consumer, and subscribe before the daemon + // up its task-scoped core-NATS subscription, and become reachable before the daemon // gives up and parks the task. ContainerPool.Acquire returns as soon // as Docker has issued the start syscall, not once that setup // finishes, so without this bound the very first request after a @@ -112,11 +109,6 @@ type Daemon struct { // lifecycle. Typed capability registries remain in their domain packages; // the host never exposes daemon internals or an untyped service locator. CapabilityHost *plugin.Host - // CustomStages discovers a repo's per-repo Yaegi custom stages - // (.archie/stages/*.go) from its prepared worktree. Set by the - // composition root (cmd/archied) to wfeval.Discover; nil disables - // discovery. - CustomStages func(dir string) ([]workflow.Stage, error) // Curators is the curator engine family registry (epic archie-core-yp9). // The runtime loop (archie-core-89x) and reference curators (i7i, gs8) // are driven through it; nil when the family is not composed. @@ -163,9 +155,7 @@ type IdentityRunner struct { // Cfg is the identity-scoped config subset (forge, models, dispatch, // budgets, etc.). Cfg config.IdentityConfig - // Agent is built from this identity's provider credentials. - Agent agentexec.Runner - Log *slog.Logger + Log *slog.Logger } // NewIdentityRunner constructs an IdentityRunner from an identity config @@ -1081,8 +1071,8 @@ func (d *Daemon) taskRunRetryBackoff() time.Duration { // requestTaskRun publishes the taskrun request and retries while no // archie-agent has subscribed yet (nats.ErrNoResponders): the container // pool's Acquire returns as soon as Docker has issued the start syscall, -// not once the spawned container has connected to NATS, set up its -// JetStream stream/consumer, and subscribed to this per-task subject -- +// not once the spawned container has connected to core NATS and subscribed +// to this per-task subject -- // a gap of hundreds of milliseconds to a few seconds that would otherwise // fail the very first request deterministically, every time, on every // task. Any error other than ErrNoResponders (encode failures, a context @@ -1140,16 +1130,11 @@ func (d *Daemon) containerEnv(task *store.Task) []string { return env } -func (d *Daemon) executionFor(task *store.Task) (config.Config, agentexec.Runner) { - if id := d.identityFor(task); id != nil { - return configForIdentity(d.Cfg.Get(), id.Cfg), id.Agent - } - return d.Cfg.Get(), d.Agent -} - func (d *Daemon) configFor(task *store.Task) config.Config { - cfg, _ := d.executionFor(task) - return cfg + if id := d.identityFor(task); id != nil { + return configForIdentity(d.Cfg.Get(), id.Cfg) + } + return d.Cfg.Get() } func configForIdentity(root config.Config, identity config.IdentityConfig) config.Config { diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index d2736ae3b..7a2f03f92 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -16,7 +16,6 @@ import ( natssrv "github.com/nats-io/nats-server/v2/test" natsio "github.com/nats-io/nats.go" - "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/domain/workintake" @@ -36,12 +35,6 @@ type cleanupStorage struct { ttl time.Duration } -type identityRunnerStub struct{} - -func (*identityRunnerStub) Run(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) { - return agentexec.Result{}, nil -} - func (s *cleanupStorage) Setup(context.Context, storage.TaskRef) ([]storage.Mount, error) { return nil, nil } @@ -479,7 +472,7 @@ func startEmbeddedNATSForDaemon(t *testing.T) *server.Server { func daemonWithNATS(t *testing.T) (*Daemon, *store.Store, *arnats.Client) { t.Helper() srv := startEmbeddedNATSForDaemon(t) - client, err := arnats.Connect(context.Background(), arnats.Config{URL: srv.ClientURL(), Subjects: []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard}, FilterSubject: workintake.SubjectTaskWildcard}, slog.New(slog.DiscardHandler)) + client, err := arnats.Connect(context.Background(), arnats.Config{URL: srv.ClientURL(), Subjects: []string{workintake.SubjectTaskWildcard}, FilterSubject: workintake.SubjectTaskWildcard}, slog.New(slog.DiscardHandler)) if err != nil { t.Fatalf("nats connect: %v", err) } @@ -1023,9 +1016,7 @@ func TestNewIdentityRunnerRejectsEmptyName(t *testing.T) { } } -func TestExecutionForUsesIdentityConfigAgentAndProvider(t *testing.T) { - rootAgent := &identityRunnerStub{} - identityAgent := &identityRunnerStub{} +func TestConfigForUsesIdentityConfigAndProvider(t *testing.T) { d := &Daemon{ Cfg: config.NewHolder(config.Config{ Models: map[string]string{"builder": "root/model"}, @@ -1033,9 +1024,8 @@ func TestExecutionForUsesIdentityConfigAgentAndProvider(t *testing.T) { "root": {Class: "openai", APIKeyEnv: "ROOT_KEY"}, }, }), - Agent: rootAgent, Identities: []*IdentityRunner{{ - Name: "worker", Agent: identityAgent, + Name: "worker", Cfg: config.IdentityConfig{ Name: "worker", Models: map[string]string{"builder": "worker/model"}, Providers: map[string]config.Provider{ @@ -1045,10 +1035,7 @@ func TestExecutionForUsesIdentityConfigAgentAndProvider(t *testing.T) { }}, } - cfg, runner := d.executionFor(&store.Task{Identity: "worker"}) - if runner != identityAgent { - t.Fatal("executionFor returned root agent for identity task") - } + cfg := d.configFor(&store.Task{Identity: "worker"}) if cfg.Models["builder"] != "worker/model" { t.Fatalf("builder model = %q", cfg.Models["builder"]) } diff --git a/internal/eventbus/eventbus.go b/internal/eventbus/eventbus.go index a12c4305c..005b3633b 100644 --- a/internal/eventbus/eventbus.go +++ b/internal/eventbus/eventbus.go @@ -17,10 +17,6 @@ var ( // never established. ErrNotConnected = errors.New("eventbus: not connected") - // ErrNoReplyAddress reports a message carrying nowhere to send a reply, - // so a request cannot be answered. - ErrNoReplyAddress = errors.New("eventbus: message has no reply address") - // ErrNoResponders reports a request sent to a subject nobody is // listening on. It is usually transient -- a worker that has connected // but not yet subscribed -- so callers typically retry within a deadline @@ -37,11 +33,6 @@ type Message interface { // Subject returns the address the message arrived on. Subject() string - // ReplyAddress returns where a response should be sent, or - // ErrNoReplyAddress when the sender expects no reply. How the address - // travels is the implementation's concern. - ReplyAddress() (string, error) - // Ack marks the message handled so it is not redelivered. Ack() error @@ -62,21 +53,6 @@ type Publisher interface { // rediscovers the same issue on every poll, so at-least-once delivery // without deduplication would enqueue it repeatedly. PublishUnique(ctx context.Context, subject, idempotencyKey string, payload []byte) error - - // PublishRequest sends payload to subject, recording replyTo as the - // address for the response. It reports ErrNoReplyAddress when replyTo is - // empty, since a request nobody can answer is a caller error rather than - // a fire-and-forget publish. - PublishRequest(ctx context.Context, subject, replyTo string, payload []byte) error - - // Respond answers a request on the address taken from - // Message.ReplyAddress. - // - // This is distinct from Publish, not a convenience over it: a reply - // address is an ephemeral inbox belonging to one waiting caller, not a - // durable subject. Sending a reply through the durable path fails, - // because the inbox is not part of any stream. - Respond(ctx context.Context, replyAddress string, payload []byte) error } // Consumer receives messages. @@ -94,24 +70,6 @@ type Consumer interface { type Requester interface { // Request sends payload to subject and waits for a single response. Request(ctx context.Context, subject string, payload []byte) ([]byte, error) - - // NewReplyInbox creates an address for one expected response. Use it when - // the reply must be awaited separately from sending, which Request cannot - // express -- publishing work and collecting its result are distinct steps - // when the responder may not exist yet. - NewReplyInbox() (ReplyInbox, error) -} - -// ReplyInbox is a one-shot address awaiting a single response. -type ReplyInbox interface { - // Subject is the address to advertise to the responder. - Subject() string - - // Next blocks until the reply arrives or ctx is done. - Next(ctx context.Context) ([]byte, error) - - // Close releases the inbox. - Close() error } // Bus is the full contract. Depend on the narrowest interface that fits: diff --git a/internal/infrastructure/agentboot/task.go b/internal/infrastructure/agentboot/task.go index 8ac59ca17..55ec9b6df 100644 --- a/internal/infrastructure/agentboot/task.go +++ b/internal/infrastructure/agentboot/task.go @@ -2,9 +2,7 @@ package agentboot import ( "encoding/json" - "errors" "fmt" - "io/fs" "os" "path/filepath" @@ -12,25 +10,22 @@ import ( ) // TaskID reads the daemon-owned boot brief at /.git/task.json. -// An absent brief selects shared-worker mode. Any other read error, malformed -// JSON, or non-positive task ID is a startup error: a container with invalid -// dedicated-task metadata must never join the shared queue. -func TaskID(mountDir string) (taskID int64, dedicated bool, err error) { +// The brief is mandatory: every worker belongs to exactly one daemon-created +// task container, so missing, unreadable, malformed, or invalid metadata is a +// startup error rather than permission to consume work for another task. +func TaskID(mountDir string) (int64, error) { path := filepath.Join(mountDir, ".git", "task.json") data, err := os.ReadFile(path) - if errors.Is(err, fs.ErrNotExist) { - return 0, false, nil - } if err != nil { - return 0, false, fmt.Errorf("read %s: %w", path, err) + return 0, fmt.Errorf("read mandatory task boot metadata %s: %w", path, err) } var payload container.TaskPayload if err := json.Unmarshal(data, &payload); err != nil { - return 0, false, fmt.Errorf("decode %s: %w", path, err) + return 0, fmt.Errorf("decode %s: %w", path, err) } if payload.ID <= 0 { - return 0, false, fmt.Errorf("decode %s: task ID must be positive, got %d", path, payload.ID) + return 0, fmt.Errorf("decode %s: task ID must be positive, got %d", path, payload.ID) } - return payload.ID, true, nil + return payload.ID, nil } diff --git a/internal/infrastructure/agentboot/task_test.go b/internal/infrastructure/agentboot/task_test.go index 987e91ac4..7084b65cd 100644 --- a/internal/infrastructure/agentboot/task_test.go +++ b/internal/infrastructure/agentboot/task_test.go @@ -18,17 +18,16 @@ func bootGitDir(t *testing.T) string { return dir } -func TestTaskIDDistinguishesSharedDedicatedAndInvalidBoots(t *testing.T) { +func TestTaskIDRequiresValidDedicatedTaskMetadata(t *testing.T) { tests := []struct { name string payload []byte write bool wantID int64 - wantOK bool wantErr bool }{ - {name: "absent uses shared mode"}, - {name: "valid uses dedicated mode", payload: mustTaskPayload(t, container.TaskPayload{ID: 42}), write: true, wantID: 42, wantOK: true}, + {name: "absent fails closed", wantErr: true}, + {name: "valid selects task", payload: mustTaskPayload(t, container.TaskPayload{ID: 42}), write: true, wantID: 42}, {name: "malformed fails closed", payload: []byte("not json"), write: true, wantErr: true}, {name: "zero ID fails closed", payload: mustTaskPayload(t, container.TaskPayload{}), write: true, wantErr: true}, {name: "negative ID fails closed", payload: mustTaskPayload(t, container.TaskPayload{ID: -1}), write: true, wantErr: true}, @@ -41,12 +40,12 @@ func TestTaskIDDistinguishesSharedDedicatedAndInvalidBoots(t *testing.T) { t.Fatal(err) } } - id, ok, err := TaskID(dir) + id, err := TaskID(dir) if (err != nil) != test.wantErr { t.Fatalf("TaskID() error = %v, wantErr %v", err, test.wantErr) } - if id != test.wantID || ok != test.wantOK { - t.Fatalf("TaskID() = (%d, %v), want (%d, %v)", id, ok, test.wantID, test.wantOK) + if id != test.wantID { + t.Fatalf("TaskID() ID = %d, want %d", id, test.wantID) } }) } @@ -59,12 +58,12 @@ func TestTaskIDFailsClosedOnNonMissingReadError(t *testing.T) { t.Fatal(err) } - id, dedicated, err := TaskID(dir) + id, err := TaskID(dir) if err == nil { t.Fatal("TaskID() error = nil for unreadable task.json path") } - if id != 0 || dedicated { - t.Fatalf("TaskID() = (%d, %v), want (0, false)", id, dedicated) + if id != 0 { + t.Fatalf("TaskID() ID = %d, want 0", id) } } diff --git a/internal/infrastructure/agentgit/safety.go b/internal/infrastructure/agentgit/safety.go index 3f895a290..1e17d6fbe 100644 --- a/internal/infrastructure/agentgit/safety.go +++ b/internal/infrastructure/agentgit/safety.go @@ -35,9 +35,10 @@ func MarkSafe(ctx context.Context, mountDir string, log *slog.Logger) bool { // the agent continues. Returns true only when git accepted the configuration. // // The guard is existence, not mount-ness: os.Stat confirms mountDir exists and -// is a directory, which is what stops archie-agent running directly on a host -// (shared queue-group mode, no container) from writing to the operator's own -// ~/.gitconfig for a path that was never created at all. It does not detect a +// is a directory, which prevents a misconfigured archie-agent from writing to +// the operator's own ~/.gitconfig for a workspace path that was never mounted. +// Mandatory task boot metadata independently rejects non-task workers before +// they subscribe. This check does not detect a // stale directory that happens to exist at the same path without actually // being a bind mount -- a real mount check would need platform-specific // parsing (e.g. /proc/self/mountinfo on Linux) that this deliberately does diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index cec2220e2..21154b706 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -5,7 +5,6 @@ package nats import ( "context" "encoding/json" - "errors" "fmt" "log/slog" "strconv" @@ -16,152 +15,69 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/domain/workflow" - "github.com/samcharles93/archie-core/internal/domain/workintake" - "github.com/samcharles93/archie-core/internal/eventbus" "github.com/samcharles93/archie-core/internal/forgerpc" - busnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/storerpc" "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/worktreerpc" ) -// Config contains the process and deployment inputs for the worker transport. -// Stream subjects, filtering, and delivery timing are transport invariants. +// Config contains the broker endpoint and credential for the worker transport. type Config struct { - URL string - Token string - ConsumerName string + URL string + Token string } const ( - stagePollTimeout = 5 * time.Second - stageAckWait = 30 * time.Minute taskSubscriptionFlushTimeout = 5 * time.Second ) -// ErrCoreConnectionUnavailable identifies failure to obtain the core-NATS -// connection after the durable bus connected successfully. -var ErrCoreConnectionUnavailable = errors.New("core NATS connection unavailable") - type sdkSubscription interface { Unsubscribe() error } -// Transport owns the worker's durable event bus and its shared core-NATS connection. +// Transport owns the worker's core-NATS connection. Full-task handoff, RPC, +// logs, and events are all request/reply or fire-and-forget core subjects; the +// worker has no JetStream consumer. type Transport struct { - bus *busnats.Client conn *natsio.Conn - subscribe func(string, natsio.MsgHandler) (sdkSubscription, error) - queueSubscribe func(string, string, natsio.MsgHandler) (sdkSubscription, error) - flush func(time.Duration) error + subscribe func(string, natsio.MsgHandler) (sdkSubscription, error) + flush func(time.Duration) error } -type busConnector func(context.Context, busnats.Config, *slog.Logger) (*busnats.Client, error) - -// Connect establishes both worker transports over one NATS connection. +// Connect establishes the worker's core-NATS connection. func Connect(ctx context.Context, config Config, log *slog.Logger) (*Transport, error) { - return connect(ctx, config, log, busnats.Connect) -} - -func connect(ctx context.Context, config Config, log *slog.Logger, connectBus busConnector) (*Transport, error) { - bus, err := connectBus(ctx, busnats.Config{ - URL: config.URL, - Token: config.Token, - Subjects: []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard}, - ConsumerName: config.ConsumerName, - FilterSubject: agentexec.SubjectAgentWildcard, - PollTimeout: stagePollTimeout, - AckWait: stageAckWait, - }, log) - if err != nil { + if log == nil { + log = slog.New(slog.DiscardHandler) + } + if err := ctx.Err(); err != nil { return nil, err } - return transportFromBus(bus) -} - -func transportFromBus(bus *busnats.Client) (*Transport, error) { - conn, err := bus.CoreConn() - if err != nil { - bus.Close() - return nil, fmt.Errorf("%w: %w", ErrCoreConnectionUnavailable, err) + options := []natsio.Option{natsio.Name("archie-agent")} + if config.Token != "" { + options = append(options, natsio.Token(config.Token)) } + conn, err := natsio.Connect(config.URL, options...) + if err != nil { + return nil, fmt.Errorf("connect core NATS: %w", err) + } + if err := ctx.Err(); err != nil { + conn.Close() + return nil, err + } + log.Info("worker transport connected", "url", conn.ConnectedUrl()) return &Transport{ - bus: bus, conn: conn, subscribe: func(subject string, handler natsio.MsgHandler) (sdkSubscription, error) { return conn.Subscribe(subject, handler) }, - queueSubscribe: func(subject, queue string, handler natsio.MsgHandler) (sdkSubscription, error) { - return conn.QueueSubscribe(subject, queue, handler) - }, flush: conn.FlushTimeout, }, nil } // Close releases all broker resources. -func (t *Transport) Close() { t.bus.Close() } - -type stageMessage struct { - wire eventbus.Message - request agentexec.AgentRequestMessage - requestErr error - replyAddress string - encode func(any) ([]byte, error) - respond func(context.Context, string, []byte) error -} - -var _ agentexec.StageMessage = (*stageMessage)(nil) - -// FetchStage receives and decodes the next durable single-stage request while -// retaining its reply inbox and acknowledgement controls inside infrastructure. -func (t *Transport) FetchStage(ctx context.Context) (agentexec.StageMessage, error) { - wire, err := t.bus.Fetch(ctx) - if err != nil { - return nil, err - } - return newStageMessage(wire, t.bus.Respond), nil -} - -func newStageMessage(wire eventbus.Message, respond func(context.Context, string, []byte) error) agentexec.StageMessage { - message := &stageMessage{wire: wire, encode: json.Marshal, respond: respond} - if err := json.Unmarshal(wire.Data(), &message.request); err != nil { - message.requestErr = fmt.Errorf("decode request: %w", err) - return message - } - var err error - message.replyAddress, err = wire.ReplyAddress() - if err != nil { - message.requestErr = fmt.Errorf("stage request on %s: %w", wire.Subject(), err) - } - return message -} - -func (m *stageMessage) Request() (agentexec.AgentRequestMessage, error) { - return m.request, m.requestErr -} - -func (m *stageMessage) Respond(ctx context.Context, response *agentexec.AgentResponseEnvelope) error { - data, err := m.encode(response) - if err != nil { - return fmt.Errorf("encode response: %w", err) - } - if err := m.respond(ctx, m.replyAddress, data); err != nil { - return fmt.Errorf("publish response: %w", err) - } - return nil -} - -func (m *stageMessage) Ack() error { return m.wire.Ack() } -func (m *stageMessage) Nak() error { return m.wire.Nak() } - -func (m *stageMessage) LogAttributes() []any { - if m.replyAddress == "" { - return nil - } - return []any{"reply_to", m.replyAddress} -} +func (t *Transport) Close() { t.conn.Close() } // LogPublisher returns the narrow fire-and-forget capability used by system logs. func (t *Transport) LogPublisher() agentexec.LogPublisher { return t.conn } @@ -208,9 +124,7 @@ type subscription struct{ sub sdkSubscription } func (s subscription) Close() error { return s.sub.Unsubscribe() } const ( - taskRunSubjectPrefix = "archie.taskrun." - taskRunSubjectWildcard = taskRunSubjectPrefix + ">" - taskRunQueueGroup = "archie-taskrun-workers" + taskRunSubjectPrefix = "archie.taskrun." ) // SubjectForTask returns the canonical core-NATS subject for one full-task handoff. @@ -230,38 +144,23 @@ func taskIDFromSubject(subject string) (int64, error) { return taskID, nil } -// SubscribeTasks selects a dedicated task subject when a boot ID is present, -// otherwise the shared worker queue. Wire decoding and inbox replies remain here. -func (t *Transport) SubscribeTasks(ctx context.Context, taskID int64, dedicated bool, handler TaskHandler, log *slog.Logger) (Subscription, error) { - callback := func(msg *natsio.Msg) { t.handleTask(ctx, msg, taskID, dedicated, handler, log) } +// SubscribeTasks serves the one task named by the worker's mandatory boot +// metadata. Wire decoding, task correlation, and inbox replies remain here. +func (t *Transport) SubscribeTasks(ctx context.Context, taskID int64, handler TaskHandler, log *slog.Logger) (Subscription, error) { + callback := func(msg *natsio.Msg) { t.handleTask(ctx, msg, taskID, handler, log) } subscribe := t.subscribe if subscribe == nil { subscribe = func(subject string, handler natsio.MsgHandler) (sdkSubscription, error) { return t.conn.Subscribe(subject, handler) } } - queueSubscribe := t.queueSubscribe - if queueSubscribe == nil { - queueSubscribe = func(subject, queue string, handler natsio.MsgHandler) (sdkSubscription, error) { - return t.conn.QueueSubscribe(subject, queue, handler) - } - } flush := t.flush if flush == nil { flush = t.conn.FlushTimeout } - var ( - sub sdkSubscription - err error - ) - if dedicated { - log.Info("taskrun: dedicated per-task subscription", "task", taskID) - sub, err = subscribe(SubjectForTask(taskID), callback) - } else { - log.Info("taskrun: shared queue-group subscription (no .git/task.json found)") - sub, err = queueSubscribe(taskRunSubjectWildcard, taskRunQueueGroup, callback) - } + log.Info("taskrun: dedicated per-task subscription", "task", taskID) + sub, err := subscribe(SubjectForTask(taskID), callback) if err != nil { return nil, err } @@ -278,7 +177,6 @@ func (t *Transport) handleTask( ctx context.Context, msg *natsio.Msg, bootTaskID int64, - dedicated bool, handler TaskHandler, log *slog.Logger, ) { @@ -288,7 +186,7 @@ func (t *Transport) handleTask( t.respondTask(msg, nil, fmt.Errorf("decode taskrun request: %w", err), log) return } - if err := validateTaskRequest(msg.Subject, request, bootTaskID, dedicated); err != nil { + if err := validateTaskRequest(msg.Subject, request, bootTaskID); err != nil { log.Error("taskrun validation failed", "subject", msg.Subject, "err", err) t.respondTask(msg, nil, fmt.Errorf("validate taskrun request: %w", err), log) return @@ -297,7 +195,7 @@ func (t *Transport) handleTask( t.respondTask(msg, response, err, log) } -func validateTaskRequest(subject string, request taskrun.Request, bootTaskID int64, dedicated bool) error { +func validateTaskRequest(subject string, request taskrun.Request, bootTaskID int64) error { subjectTaskID, err := taskIDFromSubject(subject) if err != nil { return err @@ -308,8 +206,8 @@ func validateTaskRequest(subject string, request taskrun.Request, bootTaskID int if request.Task.ID != subjectTaskID { return fmt.Errorf("task ID %d does not match subject task ID %d", request.Task.ID, subjectTaskID) } - if dedicated && subjectTaskID != bootTaskID { - return fmt.Errorf("task ID %d does not match dedicated boot task ID %d", subjectTaskID, bootTaskID) + if subjectTaskID != bootTaskID { + return fmt.Errorf("task ID %d does not match boot task ID %d", subjectTaskID, bootTaskID) } return nil } diff --git a/internal/infrastructure/agenttransport/nats/transport_test.go b/internal/infrastructure/agenttransport/nats/transport_test.go index d4e42b30c..69ffa25b2 100644 --- a/internal/infrastructure/agenttransport/nats/transport_test.go +++ b/internal/infrastructure/agenttransport/nats/transport_test.go @@ -6,7 +6,7 @@ import ( "encoding/json" "errors" "log/slog" - "reflect" + "os" "strings" "testing" "time" @@ -15,16 +15,25 @@ import ( natstest "github.com/nats-io/nats-server/v2/test" natsio "github.com/nats-io/nats.go" - "github.com/samcharles93/archie-core/internal/agentexec" - "github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/forgerpc" - busnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/storerpc" "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/worktreerpc" ) +func TestTransportContainsNoSharedTaskWorkerTopology(t *testing.T) { + source, err := os.ReadFile("transport.go") + if err != nil { + t.Fatal(err) + } + for _, forbidden := range []string{"QueueSubscribe", "taskRunSubjectWildcard", "taskRunQueueGroup"} { + if strings.Contains(string(source), forbidden) { + t.Errorf("transport.go contains forbidden shared-worker mechanism %q", forbidden) + } + } +} + func testTransport(t *testing.T) (*Transport, *natsio.Conn) { t.Helper() srv := natstest.RunRandClientPortServer() @@ -72,56 +81,56 @@ func TestTaskRunSubjectOwnsCanonicalNATSTopology(t *testing.T) { } } -func TestSubscribeTasksPreservesDedicatedAndSharedSubjects(t *testing.T) { - tests := []struct { - name string - taskID int64 - dedicated bool - subject string - requestID int64 - }{ - {name: "dedicated", taskID: 42, dedicated: true, subject: SubjectForTask(42), requestID: 42}, - {name: "shared queue", subject: SubjectForTask(7), requestID: 7}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - transport, conn := testTransport(t) - calls := 0 - subscription, err := transport.SubscribeTasks(t.Context(), test.taskID, test.dedicated, func(_ context.Context, request taskrun.Request) (*taskrun.Response, error) { - calls++ - if request.Task.ID != test.requestID { - t.Fatalf("task ID = %d, want %d", request.Task.ID, test.requestID) - } - return &taskrun.Response{Status: "done"}, nil - }, slog.New(slog.DiscardHandler)) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = subscription.Close() }) +// Full-task handoff and all worker RPC use core NATS. The worker must connect +// to a broker with JetStream disabled; requiring a durable consumer would mean +// the deleted per-stage transport still owns startup. +func TestConnectRequiresOnlyCoreNATS(t *testing.T) { + srv := natstest.RunServer(&server.Options{Port: -1, Authorization: "worker-secret"}) + t.Cleanup(srv.Shutdown) - payload, err := json.Marshal(taskrun.Request{Task: &store.Task{ID: test.requestID}, WorktreeGrant: "grant"}) - if err != nil { - t.Fatal(err) - } - message, err := conn.Request(test.subject, payload, time.Second) - if err != nil { - t.Fatal(err) - } - var response taskrun.Response - if err := json.Unmarshal(message.Data, &response); err != nil { - t.Fatal(err) - } - if calls != 1 || response.Status != "done" { - t.Fatalf("handler/response = (%d, %q), want (1, done)", calls, response.Status) - } - }) + transport, err := Connect(t.Context(), Config{URL: srv.ClientURL(), Token: "worker-secret"}, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatalf("Connect to core-only NATS: %v", err) + } + transport.Close() +} + +func TestSubscribeTasksServesOnlyBootTaskSubject(t *testing.T) { + transport, conn := testTransport(t) + calls := 0 + subscription, err := transport.SubscribeTasks(t.Context(), 42, func(_ context.Context, request taskrun.Request) (*taskrun.Response, error) { + calls++ + if request.Task.ID != 42 { + t.Fatalf("task ID = %d, want 42", request.Task.ID) + } + return &taskrun.Response{Status: "done"}, nil + }, slog.New(slog.DiscardHandler)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = subscription.Close() }) + + payload, err := json.Marshal(taskrun.Request{Task: &store.Task{ID: 42}, WorktreeGrant: "grant"}) + if err != nil { + t.Fatal(err) + } + message, err := conn.Request(SubjectForTask(42), payload, time.Second) + if err != nil { + t.Fatal(err) + } + var response taskrun.Response + if err := json.Unmarshal(message.Data, &response); err != nil { + t.Fatal(err) + } + if calls != 1 || response.Status != "done" { + t.Fatalf("handler/response = (%d, %q), want (1, done)", calls, response.Status) } } func TestSubscribeTasksOwnsWireErrors(t *testing.T) { transport, conn := testTransport(t) handlerCalls := 0 - subscription, err := transport.SubscribeTasks(t.Context(), 9, true, func(context.Context, taskrun.Request) (*taskrun.Response, error) { + subscription, err := transport.SubscribeTasks(t.Context(), 9, func(context.Context, taskrun.Request) (*taskrun.Response, error) { handlerCalls++ return nil, errors.New("run failed") }, slog.New(slog.DiscardHandler)) @@ -169,7 +178,6 @@ func TestHandleTaskRejectsSubjectCorrelationErrors(t *testing.T) { name string subject string bootTaskID int64 - dedicated bool requestID int64 want string }{ @@ -180,19 +188,18 @@ func TestHandleTaskRejectsSubjectCorrelationErrors(t *testing.T) { want: `validate taskrun request: invalid taskrun subject "archie.taskrun.invalid"`, }, { - name: "dedicated boot mismatch", + name: "boot mismatch", subject: SubjectForTask(9), bootTaskID: 42, - dedicated: true, requestID: 9, - want: "validate taskrun request: task ID 9 does not match dedicated boot task ID 42", + want: "validate taskrun request: task ID 9 does not match boot task ID 42", }, } { t.Run(test.name, func(t *testing.T) { transport, conn := testTransport(t) handlerCalls := 0 subscription, err := conn.Subscribe(test.subject, func(message *natsio.Msg) { - transport.handleTask(t.Context(), message, test.bootTaskID, test.dedicated, func(context.Context, taskrun.Request) (*taskrun.Response, error) { + transport.handleTask(t.Context(), message, test.bootTaskID, func(context.Context, taskrun.Request) (*taskrun.Response, error) { handlerCalls++ return &taskrun.Response{Status: "unexpected"}, nil }, slog.New(slog.DiscardHandler)) @@ -239,24 +246,20 @@ func (s *recordingSDKSubscription) Unsubscribe() error { func TestSubscribeTasksReportsSetupFailuresAndCleansUpFlushFailure(t *testing.T) { subscribeErr := errors.New("subscribe failed") - queueErr := errors.New("queue subscribe failed") flushErr := errors.New("flush failed") cleanupErr := errors.New("unsubscribe failed") tests := []struct { name string - dedicated bool subscribeErr error - queueErr error flushErr error cleanupErr error wantErr error wantUnsubscribes int wantCleanupLog bool }{ - {name: "direct subscribe", dedicated: true, subscribeErr: subscribeErr, wantErr: subscribeErr}, - {name: "queue subscribe", queueErr: queueErr, wantErr: queueErr}, - {name: "flush cleanup succeeds", dedicated: true, flushErr: flushErr, wantErr: flushErr, wantUnsubscribes: 1}, - {name: "flush cleanup fails", dedicated: true, flushErr: flushErr, cleanupErr: cleanupErr, wantErr: flushErr, wantUnsubscribes: 1, wantCleanupLog: true}, + {name: "direct subscribe", subscribeErr: subscribeErr, wantErr: subscribeErr}, + {name: "flush cleanup succeeds", flushErr: flushErr, wantErr: flushErr, wantUnsubscribes: 1}, + {name: "flush cleanup fails", flushErr: flushErr, cleanupErr: cleanupErr, wantErr: flushErr, wantUnsubscribes: 1, wantCleanupLog: true}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -265,9 +268,6 @@ func TestSubscribeTasksReportsSetupFailuresAndCleansUpFlushFailure(t *testing.T) subscribe: func(string, natsio.MsgHandler) (sdkSubscription, error) { return sub, test.subscribeErr }, - queueSubscribe: func(string, string, natsio.MsgHandler) (sdkSubscription, error) { - return sub, test.queueErr - }, flush: func(timeout time.Duration) error { if timeout != taskSubscriptionFlushTimeout { t.Fatalf("flush timeout = %s, want %s", timeout, taskSubscriptionFlushTimeout) @@ -276,7 +276,7 @@ func TestSubscribeTasksReportsSetupFailuresAndCleansUpFlushFailure(t *testing.T) }, } var output bytes.Buffer - _, err := transport.SubscribeTasks(t.Context(), 42, test.dedicated, func(context.Context, taskrun.Request) (*taskrun.Response, error) { + _, err := transport.SubscribeTasks(t.Context(), 42, func(context.Context, taskrun.Request) (*taskrun.Response, error) { t.Fatal("handler called") return nil, nil }, slog.New(slog.NewTextHandler(&output, nil))) @@ -293,127 +293,6 @@ func TestSubscribeTasksReportsSetupFailuresAndCleansUpFlushFailure(t *testing.T) } } -func TestConnectOwnsWorkerTopology(t *testing.T) { - connectErr := errors.New("stop after config capture") - var got busnats.Config - _, err := connect(t.Context(), Config{ - URL: "nats://worker.test:4222", - Token: "secret", - ConsumerName: "agent-worker", - }, slog.New(slog.DiscardHandler), func(_ context.Context, config busnats.Config, _ *slog.Logger) (*busnats.Client, error) { - got = config - return nil, connectErr - }) - if !errors.Is(err, connectErr) { - t.Fatalf("connect error = %v, want %v", err, connectErr) - } - if got.URL != "nats://worker.test:4222" || got.Token != "secret" || got.ConsumerName != "agent-worker" { - t.Fatalf("deployment config = %#v", got) - } - wantSubjects := []string{workintake.SubjectTaskWildcard, agentexec.SubjectAgentWildcard} - if !reflect.DeepEqual(got.Subjects, wantSubjects) { - t.Fatalf("subjects = %v, want %v", got.Subjects, wantSubjects) - } - if got.FilterSubject != agentexec.SubjectAgentWildcard || got.PollTimeout != stagePollTimeout || got.AckWait != stageAckWait { - t.Fatalf("topology config = %#v, want filter=%q poll=%s ack=%s", got, agentexec.SubjectAgentWildcard, stagePollTimeout, stageAckWait) - } -} - -type rawStageMessage struct { - data []byte - subject string - reply string - replyErr error - ackErr error - nakErr error - ackCalls int - nakCalls int -} - -func (m *rawStageMessage) Data() []byte { return m.data } -func (m *rawStageMessage) Subject() string { return m.subject } -func (m *rawStageMessage) ReplyAddress() (string, error) { return m.reply, m.replyErr } -func (m *rawStageMessage) Ack() error { m.ackCalls++; return m.ackErr } -func (m *rawStageMessage) Nak() error { m.nakCalls++; return m.nakErr } - -func TestStageMessageOwnsDecodeReplyAndAcknowledgement(t *testing.T) { - replyErr := errors.New("no reply") - for _, test := range []struct { - name string - wire *rawStageMessage - wantErr string - }{ - {name: "decode", wire: &rawStageMessage{data: []byte("not json"), subject: "archie.agent.bad"}, wantErr: "decode request:"}, - {name: "reply", wire: &rawStageMessage{data: []byte(`{"task_id":7}`), subject: "archie.agent.no-reply", replyErr: replyErr}, wantErr: "stage request on archie.agent.no-reply:"}, - {name: "typed request", wire: &rawStageMessage{data: []byte(`{"task_id":7,"stage":"test"}`), reply: "_INBOX.7"}}, - } { - t.Run(test.name, func(t *testing.T) { - message := newStageMessage(test.wire, func(context.Context, string, []byte) error { return nil }) - request, err := message.Request() - if test.wantErr != "" { - if err == nil || !strings.Contains(err.Error(), test.wantErr) { - t.Fatalf("Request error = %v, want containing %q", err, test.wantErr) - } - } else if err != nil || request.TaskID != 7 || request.Stage != "test" { - t.Fatalf("Request = (%#v, %v), want typed task 7/test", request, err) - } - if err := message.Ack(); err != nil { - t.Fatal(err) - } - if err := message.Nak(); err != nil { - t.Fatal(err) - } - if test.wire.ackCalls != 1 || test.wire.nakCalls != 1 { - t.Fatalf("ack/nak calls = (%d,%d), want (1,1)", test.wire.ackCalls, test.wire.nakCalls) - } - }) - } -} - -func TestStageMessageDelegatesAcknowledgementErrors(t *testing.T) { - ackErr := errors.New("ack failed") - nakErr := errors.New("nak failed") - wire := &rawStageMessage{data: []byte(`{"task_id":7}`), reply: "_INBOX.7", ackErr: ackErr, nakErr: nakErr} - message := newStageMessage(wire, func(context.Context, string, []byte) error { return nil }) - if err := message.Ack(); !errors.Is(err, ackErr) { - t.Fatalf("Ack error = %v, want %v", err, ackErr) - } - if err := message.Nak(); !errors.Is(err, nakErr) { - t.Fatalf("Nak error = %v, want %v", err, nakErr) - } -} - -func TestStageMessageOwnsResponseEncodingAndInboxDelivery(t *testing.T) { - encodeErr := errors.New("encode failed") - respondErr := errors.New("respond failed") - response := &agentexec.AgentResponseEnvelope{Result: agentexec.Result{Status: agentexec.StatusPassed}} - - wire := &rawStageMessage{data: []byte(`{"task_id":7}`), reply: "_INBOX.7"} - message := newStageMessage(wire, func(_ context.Context, reply string, data []byte) error { - if reply != "_INBOX.7" || !strings.Contains(string(data), `"status":"passed"`) { - t.Fatalf("reply/data = (%q,%s)", reply, data) - } - return nil - }) - if err := message.Respond(t.Context(), response); err != nil { - t.Fatal(err) - } - - concrete, ok := message.(*stageMessage) - if !ok { - t.Fatalf("message type = %T, want *stageMessage", message) - } - concrete.encode = func(any) ([]byte, error) { return nil, encodeErr } - if err := concrete.Respond(t.Context(), response); !errors.Is(err, encodeErr) || !strings.Contains(err.Error(), "encode response") { - t.Fatalf("encode error = %v", err) - } - concrete.encode = json.Marshal - concrete.respond = func(context.Context, string, []byte) error { return respondErr } - if err := concrete.Respond(t.Context(), response); !errors.Is(err, respondErr) || !strings.Contains(err.Error(), "publish response") { - t.Fatalf("respond error = %v", err) - } -} - func TestRPCFactoriesPreserveIdentityAndTimeout(t *testing.T) { transport, _ := testTransport(t) timeout := 60 * time.Second @@ -430,32 +309,3 @@ func TestRPCFactoriesPreserveIdentityAndTimeout(t *testing.T) { t.Fatalf("tree client = %#v", treeClient) } } - -func TestTransportFromBusClassifiesUnavailableCoreConnection(t *testing.T) { - transport, err := transportFromBus(&busnats.Client{}) - if transport != nil { - t.Fatalf("transport = %#v, want nil", transport) - } - if !errors.Is(err, ErrCoreConnectionUnavailable) { - t.Fatalf("error = %v, want ErrCoreConnectionUnavailable", err) - } -} - -func TestConnectOwnsJetStreamAndCoreConnection(t *testing.T) { - srv := natstest.RunRandClientPortServer() - t.Cleanup(srv.Shutdown) - if err := srv.EnableJetStream(&server.JetStreamConfig{StoreDir: t.TempDir()}); err != nil { - t.Fatal(err) - } - transport, err := Connect(t.Context(), Config{ - URL: srv.ClientURL(), - ConsumerName: "worker-test", - }, slog.New(slog.DiscardHandler)) - if err != nil { - t.Fatal(err) - } - transport.Close() - if _, err := transport.FetchStage(t.Context()); err == nil { - t.Fatal("FetchStage after Close returned nil error") - } -} diff --git a/internal/infrastructure/configuration/apply_test.go b/internal/infrastructure/configuration/apply_test.go index ca15cbd20..aef59645c 100644 --- a/internal/infrastructure/configuration/apply_test.go +++ b/internal/infrastructure/configuration/apply_test.go @@ -55,11 +55,11 @@ func TestLoaderApplyOverlayLayersDefaultsValidatesAndRecordsProvenance(t *testin // An overlay that fails validation aborts; ApplyOverlay never mutates // its input, so the base document is untouched even without a copy. - if _, err := l.ApplyOverlay(doc, map[string]any{"agent": map[string]any{"mode": "bogus"}}); err == nil { + if _, err := l.ApplyOverlay(doc, map[string]any{"dispatch": map[string]any{"trigger": "bogus"}}); err == nil { t.Fatal("invalid overlay accepted") } - if doc.Config.Agent.Mode != "inprocess" { - t.Errorf("base Agent.Mode = %q, want inprocess (defaulted, untouched)", doc.Config.Agent.Mode) + if doc.Config.Dispatch.Trigger != "assignee" { + t.Errorf("base Dispatch.Trigger = %q, want assignee (defaulted, untouched)", doc.Config.Dispatch.Trigger) } } diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 53a06835e..e7eb88fe7 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -19,7 +19,6 @@ const ( defaultMaxRetries = 3 defaultForgeType = "github" defaultForgeHost = "https://github.com" - defaultAgentCommand = "archie-agent" defaultDispatchTrigger = "assignee" defaultAckReaction = "eyes" defaultContainerUptime = 60 * time.Minute @@ -61,7 +60,6 @@ const ( func (l *Loader) applyDefaults(cfg *config.Config) { l.applyGeneralDefaults(cfg) applyForgeDefaults(cfg) - applyAgentDefaults(cfg) applyDispatchDefaults(cfg) applyIdentityDefaults(cfg) applyContainerDefaults(cfg) @@ -206,21 +204,6 @@ func applyNATSDefaults(cfg *config.Config) { } } -// applyAgentDefaults picks the execution mode. Containers require the NATS -// transport, so enabling them selects it unless the operator said otherwise. -func applyAgentDefaults(cfg *config.Config) { - if cfg.Agent.Mode == "" { - if cfg.Containers.Enabled { - cfg.Agent.Mode = agentModeNATS - } else { - cfg.Agent.Mode = agentModeInProcess - } - } - if cfg.Agent.Command == "" { - cfg.Agent.Command = defaultAgentCommand - } -} - // applyDispatchDefaults fills the dispatch section. "off" is the documented // way to disable the acknowledgement reaction, and normalises to empty. func applyDispatchDefaults(cfg *config.Config) { diff --git a/internal/infrastructure/configuration/loader_test.go b/internal/infrastructure/configuration/loader_test.go index 56786354c..c8fce5325 100644 --- a/internal/infrastructure/configuration/loader_test.go +++ b/internal/infrastructure/configuration/loader_test.go @@ -195,9 +195,6 @@ func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) { extra string }{ {name: "dispatch trigger", extra: "\n[dispatch]\ntrigger = \"labels\"\n"}, - {name: "agent mode", extra: "\n[agent]\nmode = \"remote\"\n"}, - {name: "agent command", extra: "\n[agent]\nmode = \"subprocess\"\ncommand = \" \"\n"}, - {name: "agent env", extra: "\n[agent]\nenv = [\"TOKEN=value\"]\n"}, {name: "provider userinfo", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://token@example.com/v1\"\n"}, {name: "provider query secret", extra: "\n[providers.openai]\nclass = \"openai\"\nbase_url = \"https://example.com/v1?api_key=secret\"\n"}, {name: "test glob", extra: "\n[[repos]]\nowner = \"acme\"\nname = \"app\"\ntest_glob = \"[\"\n"}, @@ -222,7 +219,7 @@ func TestLoadRejectsInvalidConfigEnumsAndGlobs(t *testing.T) { } } -func TestLoadAgentDefaultsAndOverrides(t *testing.T) { +func TestLoadLegacyAgentSectionWithoutApplyingExecutionDefaults(t *testing.T) { tests := []struct { name string agent string @@ -230,10 +227,10 @@ func TestLoadAgentDefaultsAndOverrides(t *testing.T) { wantCommand string wantEnv []string }{ - {name: "defaults", wantMode: "inprocess", wantCommand: "archie-agent"}, + {name: "absent section stays empty"}, { - name: "subprocess", agent: "\n[agent]\nmode = \"subprocess\"\ncommand = \"/opt/archie-agent\"\nenv = [\"GOCACHE\"]\n", - wantMode: "subprocess", wantCommand: "/opt/archie-agent", wantEnv: []string{"GOCACHE"}, + name: "legacy values decode without validation", agent: "\n[agent]\nmode = \"removed-mode\"\ncommand = \"/opt/old-agent\"\nenv = [\"TOKEN=value\"]\n", + wantMode: "removed-mode", wantCommand: "/opt/old-agent", wantEnv: []string{"TOKEN=value"}, }, } for _, tt := range tests { @@ -247,8 +244,8 @@ func TestLoadAgentDefaultsAndOverrides(t *testing.T) { if err != nil { t.Fatal(err) } - if cfg.Agent.Mode != tt.wantMode || cfg.Agent.Command != tt.wantCommand || strings.Join(cfg.Agent.Env, ",") != strings.Join(tt.wantEnv, ",") { - t.Fatalf("agent config = %#v", cfg.Agent) + if cfg.LegacyAgent.Mode != tt.wantMode || cfg.LegacyAgent.Command != tt.wantCommand || strings.Join(cfg.LegacyAgent.Env, ",") != strings.Join(tt.wantEnv, ",") { + t.Fatalf("legacy agent config = %#v", cfg.LegacyAgent) } }) } @@ -425,7 +422,6 @@ func TestLoadContainerVolumeTTL(t *testing.T) { t.Run(tt.name, func(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") contents := "bot_user = \"widget\"\n" + - "[agent]\nmode = \"nats\"\n" + "[nats]\nurl = \"nats://localhost:4222\"\n" + "[containers]\nenabled = true\nimage = \"archie-agent:test\"\n" + tt.ttl + "[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n" @@ -447,7 +443,6 @@ func TestLoadContainerVolumeTTL(t *testing.T) { func TestLoadRejectsNegativeContainerVolumeTTL(t *testing.T) { path := filepath.Join(t.TempDir(), "config.toml") contents := "bot_user = \"widget\"\n" + - "[agent]\nmode = \"nats\"\n" + "[nats]\nurl = \"nats://localhost:4222\"\n" + "[containers]\nenabled = true\nimage = \"archie-agent:test\"\nvolume_ttl = \"-1h\"\n" + "[[repos]]\nowner = \"acme\"\nname = \"app\"\npersistent_storage = true\n" @@ -508,8 +503,8 @@ func TestOverlay(t *testing.T) { if cfg.WorkDir != "/var/lib/archie/work" { t.Errorf("WorkDir: got %q, want overlay value", cfg.WorkDir) } - if cfg.Agent.Mode != "nats" { - t.Errorf("Agent.Mode: got %q, want %q", cfg.Agent.Mode, "nats") + if cfg.LegacyAgent.Mode != "nats" { + t.Errorf("LegacyAgent.Mode: got %q, want %q", cfg.LegacyAgent.Mode, "nats") } // Fields the overlay omits keep the base value. if cfg.BotUser != "widget" { @@ -524,8 +519,8 @@ func TestOverlay(t *testing.T) { if err != nil { t.Fatal(err) } - if baseOnly.Agent.Mode != "inprocess" { - t.Errorf("Agent.Mode with empty overlay: got %q, want %q", baseOnly.Agent.Mode, "inprocess") + if baseOnly.LegacyAgent.Mode != "inprocess" { + t.Errorf("LegacyAgent.Mode with empty overlay: got %q, want %q", baseOnly.LegacyAgent.Mode, "inprocess") } } diff --git a/internal/infrastructure/configuration/validate.go b/internal/infrastructure/configuration/validate.go index 1ebc97cad..f9e87f156 100644 --- a/internal/infrastructure/configuration/validate.go +++ b/internal/infrastructure/configuration/validate.go @@ -14,10 +14,6 @@ import ( // Recognised enum values, named so validation and its error message cannot // disagree about what is allowed. const ( - agentModeInProcess = "inprocess" - agentModeSubprocess = "subprocess" - agentModeNATS = "nats" - forgeTypeGitHub = "github" forgeTypeGitea = "gitea" forgeTypeNone = "none" @@ -30,7 +26,6 @@ const ( ) var ( - agentModes = []string{agentModeInProcess, agentModeSubprocess, agentModeNATS} forgeTypes = []string{forgeTypeGitHub, forgeTypeGitea, forgeTypeNone, forgeTypeOff, forgeTypeDisabled} dispatchTriggers = []string{dispatchTriggerAssignee, dispatchTriggerLabel, dispatchTriggerEither} natsModes = []string{config.NATSModeEmbedded, config.NATSModeExternal, config.NATSModeOff} @@ -41,8 +36,8 @@ var ( // against a config.Config value already built in memory -- e.g. by archied // setup, before it has written anything to disk. // -// Like validate, it does not apply defaults. Several checks (agent.mode, -// dispatch.trigger, forge.type) only pass once a default has been filled +// Like validate, it does not apply defaults. Several checks (dispatch.trigger, +// forge.type) only pass once a default has been filled // in, and defaulting is currently unexported ((*Loader).applyDefaults). A // cfg built by hand, with those fields left zero-valued, will fail // validation that a config loaded through [Loader.File] would pass. Callers @@ -58,9 +53,6 @@ func Validate(cfg *config.Config) error { // validate reports the first problem that would stop the daemon running. // It does not modify cfg -- run applyDefaults first. func validate(cfg *config.Config) error { - if err := validateAgent(cfg); err != nil { - return err - } if err := validateDispatch(cfg); err != nil { return err } @@ -127,21 +119,6 @@ func validatePollInterval(cfg *config.Config) error { return nil } -func validateAgent(cfg *config.Config) error { - if !oneOf(cfg.Agent.Mode, agentModes) { - return fmt.Errorf("%w: agent.mode %q (want %s)", ErrInvalidInput, cfg.Agent.Mode, list(agentModes)) - } - if cfg.Agent.Mode == agentModeSubprocess && strings.TrimSpace(cfg.Agent.Command) == "" { - return fmt.Errorf("%w: agent.command is required in subprocess mode", ErrInvalidInput) - } - for i, name := range cfg.Agent.Env { - if strings.TrimSpace(name) == "" || strings.Contains(name, "=") { - return fmt.Errorf("%w: agent.env[%d] %q is not an environment variable name", ErrInvalidInput, i, name) - } - } - return nil -} - // validateDispatch rejects a "label" or "either" trigger left with no label // to match. GitHub's issues-list API treats an empty label filter as no // filter at all and returns every open issue in the repo -- a live incident @@ -297,9 +274,6 @@ func validateNATS(cfg *config.Config) error { return fmt.Errorf("%w: nats.url must be empty when nats.mode is %q", ErrInvalidInput, mode) } } - if cfg.Agent.Mode == agentModeNATS && mode == config.NATSModeEmbedded && !cfg.Containers.Enabled { - return fmt.Errorf("%w: containers.enabled must be true when agent.mode is %q and nats.mode is %q", ErrInvalidInput, agentModeNATS, config.NATSModeEmbedded) - } return nil } @@ -313,9 +287,6 @@ func validateContainers(cfg *config.Config) error { if cfg.Containers.Image == "" { return fmt.Errorf("%w: containers.image is required when containers.enabled is true", ErrInvalidInput) } - if cfg.Agent.Mode != agentModeNATS { - return fmt.Errorf("%w: agent.mode must be %q when containers.enabled is true", ErrInvalidInput, agentModeNATS) - } if effectiveNATSMode(cfg) == config.NATSModeOff { return fmt.Errorf("%w: nats.mode must not be %q when containers.enabled is true", ErrInvalidInput, config.NATSModeOff) } diff --git a/internal/infrastructure/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index b4abb4aea..7d00622ae 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -18,7 +18,6 @@ func minimalValidConfig() config.Config { return config.Config{ BotUser: "archie-bot", PollInterval: config.Duration(60 * time.Second), - Agent: config.Agent{Mode: "inprocess"}, Dispatch: config.Dispatch{ Trigger: "assignee", }, @@ -79,11 +78,6 @@ func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) { mutate: func(cfg *config.Config) { cfg.BotUser = "" }, wantErr: true, }, - { - name: "unrecognised agent.mode", - mutate: func(cfg *config.Config) { cfg.Agent.Mode = "not-a-real-mode" }, - wantErr: true, - }, { name: "unrecognised dispatch.trigger", mutate: func(cfg *config.Config) { cfg.Dispatch.Trigger = "not-a-real-trigger" }, @@ -192,16 +186,14 @@ func TestValidate_RejectsTheSameProblemsAsLoaderLoad(t *testing.T) { // TestValidateNATS pins the nats mode contract from docs/prds/embedded-nats.md: // an unset mode resolves from url without mutating cfg, external requires url, -// embedded/off forbid a url, and NATS agent execution works with either -// embedded or external broker deployment. +// embedded/off forbid a url, and full-task workers work with either embedded +// or external broker deployment. func TestValidateNATS(t *testing.T) { tests := []struct { - name string - mode string - url string - agent string - containers bool - wantErr bool + name string + mode string + url string + wantErr bool }{ {name: "unset mode with url resolves external", url: "nats://localhost:4222"}, {name: "unset mode without url resolves embedded"}, @@ -212,20 +204,11 @@ func TestValidateNATS(t *testing.T) { {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: "unknown mode", mode: "not-a-mode", wantErr: true}, - {name: "agent nats with embedded requires containers", mode: config.NATSModeEmbedded, agent: "nats", wantErr: true}, - {name: "agent nats with embedded containers", mode: config.NATSModeEmbedded, agent: "nats", containers: true}, - {name: "agent nats with external", mode: config.NATSModeExternal, url: "nats://localhost:4222", agent: "nats"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { cfg := minimalValidConfig() cfg.NATS = config.NATSConfig{Mode: tc.mode, URL: tc.url} - if tc.agent != "" { - cfg.Agent.Mode = tc.agent - } - if tc.containers { - cfg.Containers.Enabled = true - } err := validateNATS(&cfg) if tc.wantErr && err == nil { t.Fatal("validateNATS() = nil, want an error") @@ -246,7 +229,6 @@ func TestValidateContainersResolvesNATSMode(t *testing.T) { base := func() config.Config { cfg := minimalValidConfig() cfg.Containers = config.ContainerConfig{Enabled: true, Image: "archie-agent:latest"} - cfg.Agent.Mode = "nats" return cfg } diff --git a/internal/infrastructure/eventbus/nats/message.go b/internal/infrastructure/eventbus/nats/message.go index d4a5ac6ad..6a262f501 100644 --- a/internal/infrastructure/eventbus/nats/message.go +++ b/internal/infrastructure/eventbus/nats/message.go @@ -8,14 +8,6 @@ import ( "github.com/samcharles93/archie-core/internal/eventbus" ) -// replyHeader carries the requester's reply inbox. -// -// JetStream consumes a message's Reply field for its own PubAck, so the -// address travels as a header instead. That is a NATS detail: the contract -// exposes it as [eventbus.Message.ReplyAddress] and callers never name the -// header. -const replyHeader = "X-Archie-Reply" - // idempotencyHeader is JetStream's deduplication key. Messages republished // with the same value inside Config.DedupWindow are suppressed by the server. const idempotencyHeader = "Nats-Msg-Id" @@ -37,14 +29,6 @@ func (m message) Data() []byte { return m.msg.Data() } // Subject returns the subject the message arrived on. func (m message) Subject() string { return m.msg.Subject() } -// ReplyAddress returns the requester's reply inbox. -func (m message) ReplyAddress() (string, error) { - if addr := m.msg.Headers().Get(replyHeader); addr != "" { - return addr, nil - } - return "", fmt.Errorf("%w: on %s", eventbus.ErrNoReplyAddress, m.Subject()) -} - // Ack marks the message handled so JetStream will not redeliver it. func (m message) Ack() error { if err := m.msg.Ack(); err != nil { diff --git a/internal/infrastructure/eventbus/nats/publisher.go b/internal/infrastructure/eventbus/nats/publisher.go index 59c46976a..0a7d35330 100644 --- a/internal/infrastructure/eventbus/nats/publisher.go +++ b/internal/infrastructure/eventbus/nats/publisher.go @@ -23,35 +23,6 @@ func (c *Client) PublishUnique(ctx context.Context, subject, idempotencyKey stri return c.publish(ctx, &nats.Msg{Subject: subject, Data: payload, Header: header}) } -// Respond answers a request on an ephemeral reply inbox. -// -// It uses core NATS rather than the JetStream path the other publish methods -// take: the inbox is not a stream subject, so a JetStream publish to it has -// no stream to accept the message and fails. -func (c *Client) Respond(ctx context.Context, replyAddress string, payload []byte) error { - if replyAddress == "" { - return fmt.Errorf("%w: nothing to respond to", eventbus.ErrNoReplyAddress) - } - conn, err := c.connection() - if err != nil { - return fmt.Errorf("respond on %s: %w", replyAddress, err) - } - if err := conn.Publish(replyAddress, payload); err != nil { - return fmt.Errorf("respond on %s: %w", replyAddress, err) - } - return nil -} - -// PublishRequest sends a payload recording replyTo as the response address. -func (c *Client) PublishRequest(ctx context.Context, subject, replyTo string, payload []byte) error { - if replyTo == "" { - return fmt.Errorf("%w: publishing to %s", eventbus.ErrNoReplyAddress, subject) - } - header := nats.Header{} - header.Set(replyHeader, replyTo) - return c.publish(ctx, &nats.Msg{Subject: subject, Data: payload, Header: header}) -} - // publish is the single JetStream publish path, so every caller gets the same // connection check and error context. func (c *Client) publish(ctx context.Context, msg *nats.Msg) error { @@ -87,48 +58,3 @@ func (c *Client) Request(ctx context.Context, subject string, payload []byte) ([ } return msg.Data, nil } - -// replyInbox is a one-shot subscription awaiting a single response. -type replyInbox struct { - sub *nats.Subscription -} - -var _ eventbus.ReplyInbox = replyInbox{} - -// Subject is the inbox address to advertise to the responder. -func (r replyInbox) Subject() string { return r.sub.Subject } - -// Next blocks until the reply arrives or ctx is done. -func (r replyInbox) Next(ctx context.Context) ([]byte, error) { - msg, err := r.sub.NextMsgWithContext(ctx) - if err != nil { - return nil, fmt.Errorf("await reply on %s: %w", r.sub.Subject, err) - } - return msg.Data, nil -} - -// Close unsubscribes the inbox. -func (r replyInbox) Close() error { - if err := r.sub.Unsubscribe(); err != nil { - return fmt.Errorf("close reply inbox %s: %w", r.sub.Subject, err) - } - return nil -} - -// NewReplyInbox creates a unique inbox that auto-unsubscribes after one -// message. -func (c *Client) NewReplyInbox() (eventbus.ReplyInbox, error) { - conn, err := c.connection() - if err != nil { - return nil, fmt.Errorf("create reply inbox: %w", err) - } - sub, err := conn.SubscribeSync(conn.NewInbox()) - if err != nil { - return nil, fmt.Errorf("subscribe reply inbox: %w", err) - } - if err := sub.AutoUnsubscribe(1); err != nil { - _ = sub.Unsubscribe() - return nil, fmt.Errorf("configure reply inbox %s: %w", sub.Subject, err) - } - return replyInbox{sub: sub}, nil -} diff --git a/internal/skillscript/yaegi_test.go b/internal/skillscript/yaegi_test.go index cb59e8ac6..c257ca6b5 100644 --- a/internal/skillscript/yaegi_test.go +++ b/internal/skillscript/yaegi_test.go @@ -98,8 +98,8 @@ func TestRunMissingFile(t *testing.T) { // has no cancellation mechanism. A skill script that blocks forever // (select{}) wedges the calling goroutine permanently. Every other // execution path in archie-core supports context cancellation -// (exec.CommandContext in SubprocessRunner, context.Cause checks in -// InProcessRunner), but Run cannot be canceled or timed out because it +// (context.Cause checks in LoopRunner), but Run cannot be canceled or timed +// out because it // takes no context.Context and calls i.EvalPath synchronously. func TestRunBlocksIndefinitelyOnBlockingScript(t *testing.T) { path := writeScript(t, `package main diff --git a/internal/taskrun/taskrun.go b/internal/taskrun/taskrun.go index 8e88c8e7a..e49d46119 100644 --- a/internal/taskrun/taskrun.go +++ b/internal/taskrun/taskrun.go @@ -1,6 +1,5 @@ // Package taskrun defines the wire format for handing an entire task off -// from archied to archie-agent in one NATS round trip, replacing the -// per-stage AgentRequestMessage protocol for the sandboxed container path. +// from archied to archie-agent in one NATS round trip. // archie-agent runs workflow.Route and workflow.Run itself; archied's role // shrinks to worktree prepare, container acquire/release, and answering // the storerpc/forgerpc/worktreerpc calls archie-agent proxies back. diff --git a/internal/tools/provider/contract_test.go b/internal/tools/provider/contract_test.go index b5ed83556..31b5905f3 100644 --- a/internal/tools/provider/contract_test.go +++ b/internal/tools/provider/contract_test.go @@ -65,7 +65,6 @@ func TestArchiedWiresTypedProvidersAndExecutableConsumers(t *testing.T) { // calls live in the chat composition files. "chatGenerateOptions(ctx,", "toolSummaries(options.Tools)", - "agentexec.NewInProcessRunner(b.llm, log, b.toolReg)", } { if !strings.Contains(text.String(), required) { t.Errorf("archied wiring not found: %q", required) @@ -77,4 +76,7 @@ func TestArchiedWiresTypedProvidersAndExecutableConsumers(t *testing.T) { if strings.Contains(text.String(), "memManager.GetToolSchemas()") { t.Error("composition bypasses the typed memory tool provider") } + if strings.Contains(text.String(), "NewLoopRunner") { + t.Error("archied constructs a worker-local autonomous runner") + } } diff --git a/internal/webui/api_config.go b/internal/webui/api_config.go index 673811b00..6f9909ac3 100644 --- a/internal/webui/api_config.go +++ b/internal/webui/api_config.go @@ -209,7 +209,6 @@ type ConfigView struct { Models map[string]string `json:"models"` Providers map[string]ProviderView `json:"providers"` Budgets BudgetsView `json:"budgets"` - Agent AgentView `json:"agent"` Storage StorageView `json:"storage"` Containers ContainersView `json:"containers"` Web WebView `json:"web"` @@ -271,15 +270,6 @@ type BudgetsView struct { GateMaxFailures int `json:"gate_max_failures"` } -// AgentView is how archied executes autonomous stages. Env lists only -// environment variable NAMES admitted to the worker's allowlist, never -// their values. -type AgentView struct { - Mode string `json:"mode"` - Command string `json:"command,omitempty"` - Env []string `json:"env,omitempty"` -} - // StorageView is where archied keeps its state on disk. All paths, no // secrets. type StorageView struct { @@ -349,11 +339,6 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { WallClock: cfg.Budgets.WallClock.Std().String(), GateMaxFailures: cfg.Budgets.GateMaxFailures, }, - Agent: AgentView{ - Mode: cfg.Agent.Mode, - Command: cfg.Agent.Command, - Env: cfg.Agent.Env, - }, Storage: StorageView{ WorkDir: cfg.WorkDir, DBPath: cfg.DBPath, diff --git a/internal/webui/api_config_test.go b/internal/webui/api_config_test.go index 586fe73a8..d96fcbf1c 100644 --- a/internal/webui/api_config_test.go +++ b/internal/webui/api_config_test.go @@ -55,8 +55,8 @@ func configWithFakeSecrets() *config.Holder { Repos: []config.Repo{ {Owner: "acme", Name: "widget", Base: "main", Gate: [][]string{{"task", "check"}}}, }, - Agent: config.Agent{Mode: "subprocess", Command: "/usr/local/bin/archie-agent", Env: []string{"HOME"}}, - NATS: config.NATSConfig{URL: "nats://127.0.0.1:4222", TokenEnv: "NATS_TOKEN"}, + LegacyAgent: config.LegacyAgent{Mode: "subprocess", Command: "/usr/local/bin/archie-agent", Env: []string{"HOME"}}, + NATS: config.NATSConfig{URL: "nats://127.0.0.1:4222", TokenEnv: "NATS_TOKEN"}, Chat: config.ChatConfig{ Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN"}, }, @@ -140,12 +140,12 @@ func TestHandleConfigSafeFieldsPresent(t *testing.T) { if got.Providers["openai"].APIKeyEnv != "OPENAI_API_KEY" { t.Errorf("Providers[openai].APIKeyEnv = %q, want OPENAI_API_KEY", got.Providers["openai"].APIKeyEnv) } - if got.Agent.Mode != "subprocess" { - t.Errorf("Agent.Mode = %q, want subprocess", got.Agent.Mode) - } if got.Storage.WorkDir != "/work/archie" { t.Errorf("Storage.WorkDir = %q", got.Storage.WorkDir) } + if strings.Contains(w.Body.String(), `"agent"`) { + t.Errorf("removed agent execution selector leaked through config API: %s", w.Body) + } } // TestHandleConfigIncludesReloadStatus proves a failed reload is surfaced diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index 5693b5f98..ee42b9868 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -7,7 +7,7 @@ stroke-dasharray="${c}" stroke-dashoffset="${c*(1-i/100)}" class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(e){return e==null||e===``?`—`:String(e)}function K(t,n,r){let i=ie(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`—`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>se(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>ae(f,u,r)),f}function ae(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,m.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,oe(e,String(n.message||n))})}function oe(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function se(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let h=()=>n(t,...a);f.addEventListener(`click`,h),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&h()}),d.addEventListener(`click`,async()=>{let e=ce(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await m.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}var le={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ue={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function de(t){return t.length?fe(`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Component`,`Install type`,`Running`,`Latest available`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,{title:[`Installed claim: ${t.installed_claim||`unknown`}`,`Running: ${t.running_version||`not observed`}`,t.reference?`Reference: ${t.reference}`:null].filter(Boolean).join(` -`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.agent,a),Ce(t.storage,t.containers,a),Te(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n){return t?q(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.kv-list`,K(`Execution mode`,Se(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),K(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),K(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):q(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function Se(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function Ce(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,we(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function we(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Te(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var Ee=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function De(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Oe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...Ee.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Pe(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Ne(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(ke(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(ke(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ae)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function ke(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ae(t){let n=t.fields||{};return e(`div.log-row.log-${De(t.level)}`,e(`span.log-time.mono`,Me(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(je(n))))))}function je(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Me(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Ne(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pe(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Fe(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Ie(t)]:[o]}function Ie(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Le(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Le(t.headers)))))}function Le(t){return t?e(`pre.capture-payload`,Re(t)):e(`div.capture-empty`,`(empty)`)}function Re(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ze(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Fe(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Be=[`string`,`number`,`bool`,`object`,`array`,`any`];function Ve(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function He(e,t){return e?`${e}.${t}`:t}function Ue(e,t){return`${e}[${t}]`}function We(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ue(n,t)]):Object.entries(t).map(([e,t])=>[e,t,He(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:Ve(n),name:t})}},t),We(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:Ve(t),name:r})}},JSON.stringify(t))}function Ge(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Be.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,Ke(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function Ke(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function qe(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Je(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>qe(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ge(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):We(o.payload,{onPick:p})))}return t}function Ye(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Xe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Xe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ze(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ze(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Qe=`
+`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.storage,t.containers,a),Ce(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,Se(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function Se(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Ce(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var we=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function Te(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ee(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...we.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Me(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(je(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(De(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(De(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Oe)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function De(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Oe(t){let n=t.fields||{};return e(`div.log-row.log-${Te(t.level)}`,e(`span.log-time.mono`,Ae(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(ke(n))))))}function ke(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Ae(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function je(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Me(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Ne(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Pe(t)]:[o]}function Pe(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Fe(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Fe(t.headers)))))}function Fe(t){return t?e(`pre.capture-payload`,Ie(t)):e(`div.capture-empty`,`(empty)`)}function Ie(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Le(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Ne(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Re=[`string`,`number`,`bool`,`object`,`array`,`any`];function ze(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function Be(e,t){return e?`${e}.${t}`:t}function Ve(e,t){return`${e}[${t}]`}function He(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ve(n,t)]):Object.entries(t).map(([e,t])=>[e,t,Be(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:ze(n),name:t})}},t),He(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:ze(t),name:r})}},JSON.stringify(t))}function Ue(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Re.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,We(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function We(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function Ge(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Ke(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>Ge(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ue(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):He(o.payload,{onPick:p})))}return t}function qe(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Je)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Je(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ye(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ye(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Xe=`
ARCHIE WORKSPACE

Chat

@@ -72,10 +72,10 @@
-`;function $e(){let e=document.createElement(`template`);e.innerHTML=Qe.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return ii&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i{i.length&&(n.append(e(`p`,J(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;te(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` -`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function tt(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function nt(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function rt(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function it(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?et(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=et(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function at(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),ot(t).append(o),o}function ot(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var st=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(st);return e||(e=crypto.randomUUID(),localStorage.setItem(st,e)),e}function ct(e){return{text:e,sourceID:crypto.randomUUID()}}function lt(e){return{...e}}function ut(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?lt(e.turn):ct(r),isRetry:n}}function dt({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,nt(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ft(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,pt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function pt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function mt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function ht(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function gt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function _t(e){return e?.status===501?null:`Could not check for updates.`}function vt(){let{root:t,refs:n}=$e(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(it(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1,_.children[A]?.scrollIntoView({block:`nearest`})}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,ht(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),ht(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=_t(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{gt(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,ft({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=mt(y,e.commands),dt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,dt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=ut(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:rt();l||i.append(u),u.querySelector(`.chat-retry`)?.remove(),u.querySelector(`.chat-tools`)?.replaceChildren();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` +`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` +`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function $e(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function et(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function tt(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function nt(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Qe(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Qe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function rt(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),it(t).append(o),o}function it(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var at=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(at);return e||(e=crypto.randomUUID(),localStorage.setItem(at,e)),e}function ot(e){return{text:e,sourceID:crypto.randomUUID()}}function st(e){return{...e}}function ct(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?st(e.turn):ot(r),isRetry:n}}function lt({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,et(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ut(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,dt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function dt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function ft(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function pt(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function mt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function ht(e){return e?.status===501?null:`Could not check for updates.`}function gt(){let{root:t,refs:n}=Ze(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(nt(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1,_.children[A]?.scrollIntoView({block:`nearest`})}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,pt(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),pt(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=ht(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{mt(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,ut({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=ft(y,e.commands),lt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,lt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=ct(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:tt();l||i.append(u),u.querySelector(`.chat-retry`)?.remove(),u.querySelector(`.chat-tools`)?.replaceChildren();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` `);i=a.pop()||``;for(let e of a){let t=e.split(` -`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&at(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=lt(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{pt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:vt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:Oe},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:ze},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Je},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ye},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:pe}],yt=`archie.theme`;function bt(e){document.documentElement.dataset.theme=e,localStorage.setItem(yt,e)}function $(){return localStorage.getItem(yt)||`dark`}function xt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{bt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function St(){bt($());let t=e(`main.main`),r=xt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Ct(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function Ct(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}St(); \ No newline at end of file +`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&rt(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=st(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{dt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:gt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:Ee},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Le},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Ke},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:qe},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:pe}],_t=`archie.theme`;function vt(e){document.documentElement.dataset.theme=e,localStorage.setItem(_t,e)}function $(){return localStorage.getItem(_t)||`dark`}function yt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{vt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function bt(){vt($());let t=e(`main.main`),r=yt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):xt(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function xt(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}bt(); \ No newline at end of file diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 7c66d1f32..2aa35774c 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -101,7 +101,6 @@ export function settingsPage() { repositoriesCard(cfg.repositories), modelsAndProvidersCard(cfg.models, cfg.providers), budgetsCard(cfg.budgets, ctx), - agentCard(cfg.agent, ctx), storageCard(cfg.storage, cfg.containers, ctx), webCard(cfg.web, ctx), provenanceCard(cfg.provenance), @@ -247,33 +246,6 @@ function budgetsCard(budgets, ctx) { ); } -function agentCard(agent, ctx) { - if (!agent) return section("Agent execution", "How Archie runs autonomous stages.", empty("Not available")); - return section( - "Agent execution", - "How archied actually runs a stage of work.", - el( - "div.kv-list", - row("Execution mode", agentModeLabel(agent.mode), { key: "agent.mode", type: "string", raw: agent.mode, ...ctx }), - row("Worker command", agent.command, { key: "agent.command", type: "string", raw: agent.command, ...ctx }), - row("Extra environment variables passed through", agent.env?.length ? agent.env.join(", ") : "None"), - ), - ); -} - -function agentModeLabel(mode) { - switch (mode) { - case "inprocess": - return "In-process (same binary as the daemon)"; - case "subprocess": - return "Subprocess (separate archie-agent process)"; - case "nats": - return "NATS (dispatched to a worker over the message bus)"; - default: - return mode || "Not set"; - } -} - function storageCard(storage, containers, ctx) { const children = []; if (storage) {